@agent-native/core 0.20.9 → 0.22.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/action.d.ts +61 -0
- package/dist/action.d.ts.map +1 -1
- package/dist/action.js +14 -0
- package/dist/action.js.map +1 -1
- package/dist/agent/production-agent.d.ts +4 -0
- package/dist/agent/production-agent.d.ts.map +1 -1
- package/dist/agent/production-agent.js +19 -7
- package/dist/agent/production-agent.js.map +1 -1
- package/dist/agent/types.d.ts +2 -0
- package/dist/agent/types.d.ts.map +1 -1
- package/dist/agent/types.js.map +1 -1
- package/dist/cli/code-agent-executor.d.ts.map +1 -1
- package/dist/cli/code-agent-executor.js +1 -0
- package/dist/cli/code-agent-executor.js.map +1 -1
- package/dist/cli/connect.d.ts +18 -3
- package/dist/cli/connect.d.ts.map +1 -1
- package/dist/cli/connect.js +619 -19
- package/dist/cli/connect.js.map +1 -1
- package/dist/client/AgentPanel.d.ts.map +1 -1
- package/dist/client/AgentPanel.js +6 -2
- package/dist/client/AgentPanel.js.map +1 -1
- package/dist/client/AssistantChat.d.ts.map +1 -1
- package/dist/client/AssistantChat.js +13 -6
- package/dist/client/AssistantChat.js.map +1 -1
- package/dist/client/NewWorkspaceAppFlow.js +1 -1
- package/dist/client/NewWorkspaceAppFlow.js.map +1 -1
- package/dist/client/agent-chat.d.ts.map +1 -1
- package/dist/client/agent-chat.js +13 -8
- package/dist/client/agent-chat.js.map +1 -1
- package/dist/client/agent-sidebar-state.d.ts +2 -0
- package/dist/client/agent-sidebar-state.d.ts.map +1 -1
- package/dist/client/agent-sidebar-state.js +40 -0
- package/dist/client/agent-sidebar-state.js.map +1 -1
- package/dist/client/code-agent-chat-adapter.js +1 -0
- package/dist/client/code-agent-chat-adapter.js.map +1 -1
- package/dist/client/conversation/AgentConversation.d.ts.map +1 -1
- package/dist/client/conversation/AgentConversation.js +3 -2
- package/dist/client/conversation/AgentConversation.js.map +1 -1
- package/dist/client/conversation/code-agent-transcript.js +1 -0
- package/dist/client/conversation/code-agent-transcript.js.map +1 -1
- package/dist/client/conversation/types.d.ts +2 -0
- package/dist/client/conversation/types.d.ts.map +1 -1
- package/dist/client/conversation/types.js.map +1 -1
- package/dist/client/index.d.ts +1 -0
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +1 -0
- package/dist/client/index.js.map +1 -1
- package/dist/client/mcp-apps/McpAppRenderer.d.ts +10 -0
- package/dist/client/mcp-apps/McpAppRenderer.d.ts.map +1 -0
- package/dist/client/mcp-apps/McpAppRenderer.js +301 -0
- package/dist/client/mcp-apps/McpAppRenderer.js.map +1 -0
- package/dist/client/sse-event-processor.d.ts +3 -0
- package/dist/client/sse-event-processor.d.ts.map +1 -1
- package/dist/client/sse-event-processor.js +2 -0
- package/dist/client/sse-event-processor.js.map +1 -1
- package/dist/client/use-db-sync.d.ts +5 -5
- package/dist/client/use-db-sync.d.ts.map +1 -1
- package/dist/client/use-db-sync.js +15 -5
- package/dist/client/use-db-sync.js.map +1 -1
- package/dist/client/use-db-sync.spec.d.ts +2 -0
- package/dist/client/use-db-sync.spec.d.ts.map +1 -0
- package/dist/client/use-db-sync.spec.js +80 -0
- package/dist/client/use-db-sync.spec.js.map +1 -0
- package/dist/code-agents/transcript-normalizer.d.ts +2 -0
- package/dist/code-agents/transcript-normalizer.d.ts.map +1 -1
- package/dist/code-agents/transcript-normalizer.js +17 -0
- package/dist/code-agents/transcript-normalizer.js.map +1 -1
- package/dist/db/client.d.ts.map +1 -1
- package/dist/db/client.js +29 -21
- package/dist/db/client.js.map +1 -1
- package/dist/extensions/actions.d.ts.map +1 -1
- package/dist/extensions/actions.js +62 -3
- package/dist/extensions/actions.js.map +1 -1
- package/dist/extensions/content-patch.d.ts +71 -0
- package/dist/extensions/content-patch.d.ts.map +1 -0
- package/dist/extensions/content-patch.js +251 -0
- package/dist/extensions/content-patch.js.map +1 -0
- package/dist/extensions/routes.js +6 -1
- package/dist/extensions/routes.js.map +1 -1
- package/dist/extensions/store.d.ts +4 -4
- package/dist/extensions/store.d.ts.map +1 -1
- package/dist/extensions/store.js +14 -18
- package/dist/extensions/store.js.map +1 -1
- package/dist/index.browser.d.ts +1 -1
- package/dist/index.browser.d.ts.map +1 -1
- package/dist/index.browser.js +1 -1
- package/dist/index.browser.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/mcp/build-server.d.ts +3 -0
- package/dist/mcp/build-server.d.ts.map +1 -1
- package/dist/mcp/build-server.js +207 -8
- package/dist/mcp/build-server.js.map +1 -1
- package/dist/mcp/oauth-route.d.ts +22 -0
- package/dist/mcp/oauth-route.d.ts.map +1 -0
- package/dist/mcp/oauth-route.js +618 -0
- package/dist/mcp/oauth-route.js.map +1 -0
- package/dist/mcp/oauth-store.d.ts +89 -0
- package/dist/mcp/oauth-store.d.ts.map +1 -0
- package/dist/mcp/oauth-store.js +391 -0
- package/dist/mcp/oauth-store.js.map +1 -0
- package/dist/mcp/oauth-token.d.ts +28 -0
- package/dist/mcp/oauth-token.d.ts.map +1 -0
- package/dist/mcp/oauth-token.js +83 -0
- package/dist/mcp/oauth-token.js.map +1 -0
- package/dist/mcp/server.d.ts.map +1 -1
- package/dist/mcp/server.js +5 -2
- package/dist/mcp/server.js.map +1 -1
- package/dist/mcp/stdio.d.ts +2 -2
- package/dist/mcp/stdio.d.ts.map +1 -1
- package/dist/mcp/stdio.js +26 -8
- package/dist/mcp/stdio.js.map +1 -1
- package/dist/mcp-client/app-result.d.ts +40 -0
- package/dist/mcp-client/app-result.d.ts.map +1 -0
- package/dist/mcp-client/app-result.js +19 -0
- package/dist/mcp-client/app-result.js.map +1 -0
- package/dist/mcp-client/index.d.ts +5 -2
- package/dist/mcp-client/index.d.ts.map +1 -1
- package/dist/mcp-client/index.js +201 -25
- package/dist/mcp-client/index.js.map +1 -1
- package/dist/mcp-client/manager.d.ts +16 -0
- package/dist/mcp-client/manager.d.ts.map +1 -1
- package/dist/mcp-client/manager.js +58 -1
- package/dist/mcp-client/manager.js.map +1 -1
- package/dist/mcp-client/routes.d.ts +4 -1
- package/dist/mcp-client/routes.d.ts.map +1 -1
- package/dist/mcp-client/routes.js +159 -0
- package/dist/mcp-client/routes.js.map +1 -1
- package/dist/scripts/dev/shell.d.ts.map +1 -1
- package/dist/scripts/dev/shell.js +24 -1
- package/dist/scripts/dev/shell.js.map +1 -1
- package/dist/server/agent-chat-plugin.d.ts.map +1 -1
- package/dist/server/agent-chat-plugin.js +3 -2
- package/dist/server/agent-chat-plugin.js.map +1 -1
- package/dist/server/auth.d.ts.map +1 -1
- package/dist/server/auth.js +14 -8
- package/dist/server/auth.js.map +1 -1
- package/dist/server/builder-browser.d.ts +6 -0
- package/dist/server/builder-browser.d.ts.map +1 -1
- package/dist/server/builder-browser.js +15 -0
- package/dist/server/builder-browser.js.map +1 -1
- package/dist/server/core-routes-plugin.d.ts +5 -4
- package/dist/server/core-routes-plugin.d.ts.map +1 -1
- package/dist/server/core-routes-plugin.js +17 -2
- package/dist/server/core-routes-plugin.js.map +1 -1
- package/dist/styles/agent-conversation.css +53 -0
- package/dist/templates/default/.agents/skills/actions/SKILL.md +193 -72
- package/dist/templates/default/.agents/skills/real-time-sync/SKILL.md +88 -38
- package/dist/templates/default/AGENTS.md +3 -3
- package/dist/templates/default/actions/hello.ts +13 -20
- package/dist/templates/default/actions/navigate.ts +19 -51
- package/dist/templates/default/actions/view-screen.ts +16 -33
- package/dist/templates/default/app/hooks/use-navigation-state.ts +13 -3
- package/dist/templates/default/app/lib/tab-id.ts +1 -0
- package/dist/templates/default/app/root.tsx +2 -1
- package/dist/templates/default/app/routes/_index.tsx +11 -0
- package/dist/templates/default/package.json +2 -1
- package/dist/templates/workspace-core/.agents/skills/real-time-sync/SKILL.md +9 -1
- package/dist/templates/workspace-core/AGENTS.md +8 -0
- package/dist/templates/workspace-root/AGENTS.md +7 -0
- package/dist/vite/client.d.ts.map +1 -1
- package/dist/vite/client.js +2 -2
- package/dist/vite/client.js.map +1 -1
- package/docs/content/actions.md +26 -3
- package/docs/content/authentication.md +16 -1
- package/docs/content/client.md +11 -8
- package/docs/content/context-awareness.md +2 -3
- package/docs/content/creating-templates.md +2 -2
- package/docs/content/external-agents.md +106 -19
- package/docs/content/faq.md +2 -2
- package/docs/content/key-concepts.md +31 -23
- package/docs/content/mcp-clients.md +1 -1
- package/docs/content/mcp-protocol.md +65 -27
- package/docs/content/template-starter.md +3 -3
- package/docs/content/what-is-agent-native.md +4 -2
- package/package.json +3 -1
- package/src/templates/default/.agents/skills/actions/SKILL.md +193 -72
- package/src/templates/default/.agents/skills/real-time-sync/SKILL.md +88 -38
- package/src/templates/default/AGENTS.md +3 -3
- package/src/templates/default/actions/hello.ts +13 -20
- package/src/templates/default/actions/navigate.ts +19 -51
- package/src/templates/default/actions/view-screen.ts +16 -33
- package/src/templates/default/app/hooks/use-navigation-state.ts +13 -3
- package/src/templates/default/app/lib/tab-id.ts +1 -0
- package/src/templates/default/app/root.tsx +2 -1
- package/src/templates/default/app/routes/_index.tsx +11 -0
- package/src/templates/default/package.json +2 -1
- package/src/templates/workspace-core/.agents/skills/real-time-sync/SKILL.md +9 -1
- package/src/templates/workspace-core/AGENTS.md +8 -0
- package/src/templates/workspace-root/AGENTS.md +7 -0
- package/dist/templates/default/server/routes/api/hello.get.ts +0 -5
- package/dist/templates/default/shared/api.ts +0 -6
- package/src/templates/default/server/routes/api/hello.get.ts +0 -5
- package/src/templates/default/shared/api.ts +0 -6
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,mCAAmC;AACnC,+CAA+C;AAE/C,0BAA0B;AAC1B,OAAO,EACL,4BAA4B,EAU5B,aAAa,GACd,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EACL,YAAY,EACZ,oBAAoB,EACpB,sBAAsB,G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B,EACtB,2BAA2B,EAC3B,4CAA4C,EAC5C,6BAA6B,EAC7B,wBAAwB,EACxB,0CAA0C,EAC1C,2CAA2C,EAC3C,8BAA8B,EAC9B,iCAAiC,EACjC,4BAA4B,EAC5B,0CAA0C,EAC1C,6CAA6C,EAC7C,8BAA8B,EAC9B,yBAAyB,EAmCzB,mCAAmC,GACpC,MAAM,kCAAkC,CAAC;AAE1C,iDAAiD;AACjD,OAAO,EACL,gBAAgB,EAChB,0BAA0B,EAC1B,8BAA8B,EAC9B,2BAA2B,EAC3B,oBAAoB,EACpB,kCAAkC,EAClC,iCAAiC,EACjC,iBAAiB,EACjB,8BAA8B,EAC9B,+BAA+B,EAC/B,mBAAmB,EACnB,gCAAgC,EAChC,6CAA6C,EAC7C,2CAA2C,EAC3C,sBAAsB,EACtB,mCAAmC,GA2BpC,MAAM,wBAAwB,CAAC;AAEhC,UAAU;AACV,OAAO,EACL,SAAS,EACT,OAAO,EACP,SAAS,EACT,aAAa,EACb,WAAW,EACX,kBAAkB,EAClB,SAAS,EACT,IAAI,GACL,MAAM,oBAAoB,CAAC;AAE5B,4EAA4E;AAC5E,wEAAwE;AACxE,mCAAmC;AACnC,OAAO,EACL,sBAAsB,EACtB,mBAAmB,EACnB,iBAAiB,EACjB,aAAa,EACb,cAAc,EACd,eAAe,GAMhB,MAAM,oBAAoB,CAAC","sourcesContent":["// Framework for agent-native apps.\n// Import everything from \"@agent-native/core\".\n\n// Agent (production mode)\nexport {\n createProductionAgentHandler,\n type ActionEntry,\n type ScriptEntry,\n type ProductionAgentOptions,\n type ActionTool,\n type ScriptTool,\n type AgentMessage,\n type AgentChatRequest,\n type AgentChatEvent,\n type AgentChatAttachment,\n DEFAULT_MODEL,\n} from \"./agent/index.js\";\nexport {\n defineAction,\n AgentActionStopError,\n isAgentActionStopError,\n type ActionHttpConfig,\n type AgentActionStopOptions,\n type PublicAgentActionConfig,\n type ActionDeepLink,\n type ActionLinkBuilder,\n} from \"./action.js\";\nexport { createDevScriptRegistry } from \"./scripts/dev/index.js\";\nexport {\n createAgentChatPlugin,\n defaultAgentChatPlugin,\n type AgentChatPluginOptions,\n} from \"./server/agent-chat-plugin.js\";\nexport {\n createAgentNativeEmbeddedPlugin,\n mountAgentNativeEmbedded,\n type AgentNativeEmbeddedPluginOptions,\n} from \"./server/embedded.js\";\n\n// Server\nexport {\n createServer,\n createSSEHandler,\n defineNitroPlugin,\n autoMountAuth,\n getSession,\n type CreateServerOptions,\n type SSEHandlerOptions,\n type AuthSession,\n type AuthOptions,\n} from \"./server/index.js\";\n\n// Client\nexport {\n sendToAgentChat,\n useAgentChatGenerating,\n useDevMode,\n useSendToAgentChat,\n CodeRequiredDialog,\n useAgentNativeEmbeddedBrowserSession,\n useDbSync,\n useFileWatcher,\n cn,\n ApiKeySettings,\n useSession,\n AgentNativeEmbedded,\n useProductionAgent,\n ProductionAgentPanel,\n type AgentChatMessage,\n type AgentNativeEmbeddedProps,\n type UseAgentNativeEmbeddedBrowserSessionOptions,\n type CodeRequiredDialogProps,\n type ProductionAgentMessage,\n type UseProductionAgentResult,\n type ProductionAgentPanelProps,\n useActionQuery,\n useActionMutation,\n} from \"./client/index.js\";\n\n// Shared (isomorphic)\nexport {\n agentChat,\n type AgentChatCallOptions,\n type AgentChatResponse,\n} from \"./shared/index.js\";\n\n// Agent Web surfaces\nexport {\n AGENT_WEB_CRAWLER_CATEGORIES,\n AGENT_WEB_CRAWLER_USER_AGENTS,\n DEFAULT_AGENT_WEB_CRAWLER_POLICY,\n absoluteUrl,\n agentWebConfigFromPackageJson,\n buildAgentWebStaticFiles,\n buildBaseJsonLd,\n buildLlmsFullTxt,\n buildLlmsTxt,\n buildMarkdownResponseHeaders,\n buildPageJsonLd,\n buildRobotsTxt,\n buildSitemapXml,\n deriveAgentWebPublicRoutes,\n estimateMarkdownTokens,\n markdownFilePathForPage,\n markdownUrlForPage,\n normalizeAgentWebConfig,\n pathPatternMatches,\n resolveAgentWebCrawlerPolicy,\n type AgentWebConfig,\n type AgentWebCrawlerCategory,\n type AgentWebCrawlerDecision,\n type AgentWebCrawlerOverrides,\n type AgentWebCrawlerPolicy,\n type AgentWebInputConfig,\n type AgentWebPage,\n type AgentWebStaticFile,\n type BuildAgentWebStaticFilesOptions,\n type DeriveAgentWebPublicRoutesOptions,\n type MarkdownResponseHeadersOptions,\n} from \"./agent-web/index.js\";\n\n// Token usage tracking\nexport {\n recordUsage,\n getUsageSummary,\n getUserUsageCents,\n calculateCost,\n usageBillingForEngine,\n builderCreditsFromCostCents,\n BUILDER_AGENT_CREDIT_MARGIN_MULTIPLIER,\n BUILDER_AGENT_CREDITS_PER_USD,\n BUILDER_CREDIT_USAGE_BILLING,\n USD_USAGE_BILLING,\n type UsageRecord,\n type UsageSummary,\n type UsageBillingMode,\n type UsageBillingUnit,\n type UsageBucket,\n type DailyBucket,\n type UsageRecentEntry,\n} from \"./usage/store.js\";\n\n// Workspace-scoped third-party connection metadata\nexport {\n deleteWorkspaceConnection,\n getWorkspaceConnectionAppAccess,\n getWorkspaceConnection,\n getWorkspaceConnectionGrant,\n listWorkspaceConnectionProviderCatalogForApp,\n listWorkspaceConnectionGrants,\n listWorkspaceConnections,\n resolveWorkspaceConnectionCredentialForApp,\n resolveWorkspaceConnectionCredentialsForApp,\n revokeWorkspaceConnectionGrant,\n serializeWorkspaceConnectionGrant,\n serializeWorkspaceConnection,\n summarizeWorkspaceConnectionProviderForApp,\n summarizeWorkspaceConnectionProviderReadiness,\n upsertWorkspaceConnectionGrant,\n upsertWorkspaceConnection,\n type ListWorkspaceConnectionProviderCatalogForAppOptions,\n type ListWorkspaceConnectionGrantsOptions,\n type ListWorkspaceConnectionsOptions,\n type ResolveWorkspaceConnectionCredentialForAppOptions,\n type ResolveWorkspaceConnectionCredentialsForAppOptions,\n type SerializedWorkspaceConnectionGrant,\n type SerializedWorkspaceConnection,\n type SummarizeWorkspaceConnectionProviderForAppOptions,\n type SummarizeWorkspaceConnectionProviderReadinessOptions,\n type UpsertWorkspaceConnectionGrantInput,\n type UpsertWorkspaceConnectionInput,\n type WorkspaceConnectionAppAccess,\n type WorkspaceConnectionAppAccessMode,\n type WorkspaceConnection,\n type WorkspaceConnectionCredentialBackend,\n type WorkspaceConnectionCredentialProvenance,\n type WorkspaceConnectionCredentialRef,\n type WorkspaceConnectionCredentialResolution,\n type WorkspaceConnectionCredentialResolutionCheck,\n type WorkspaceConnectionCredentialResolutionStatus,\n type WorkspaceConnectionCredentialsResolution,\n type WorkspaceConnectionExplicitGrantSummary,\n type WorkspaceConnectionForAppSummary,\n type WorkspaceConnectionGrant,\n type WorkspaceConnectionGrantAvailability,\n type WorkspaceConnectionGrantState,\n type WorkspaceConnectionProviderAppSummary,\n type WorkspaceConnectionProviderLike,\n type WorkspaceConnectionProviderCatalogForApp,\n type WorkspaceConnectionProviderCatalogForAppItem,\n type WorkspaceConnectionProviderReadiness,\n type WorkspaceConnectionProviderReadinessStatus,\n type WorkspaceConnectionPublicCredentialRef,\n type WorkspaceConnectionStatus,\n workspaceConnectionIsAvailableToApp,\n} from \"./workspace-connections/index.js\";\n\n// Reusable workspace connection provider catalog\nexport {\n PROVIDER_READERS,\n ProviderReaderRuntimeError,\n WORKSPACE_CONNECTION_PROVIDERS,\n createProviderReaderRuntime,\n defineProviderReader,\n defineProviderReaderImplementation,\n defineWorkspaceConnectionProvider,\n getProviderReader,\n getWorkspaceConnectionProvider,\n isWorkspaceConnectionProviderId,\n listProviderReaders,\n listWorkspaceConnectionProviders,\n listWorkspaceConnectionProvidersForCapability,\n listWorkspaceConnectionProvidersForTemplate,\n providerReaderSupports,\n workspaceConnectionProviderSupports,\n type ListWorkspaceConnectionProvidersOptions,\n type ListProviderReadersOptions,\n type ProviderReaderCapability,\n type ProviderReaderCredentialRequirement,\n type ProviderReaderDefinition,\n type ProviderReaderImplementationStatus,\n type ProviderReaderOperation,\n type ProviderReaderOperationDescriptor,\n type ProviderReaderOperationParameter,\n type ProviderReaderRequest,\n type ProviderReaderRuntime,\n type ProviderReaderRuntimeConnection,\n type ProviderReaderRuntimeConnectionResolverOptions,\n type ProviderReaderRuntimeContext,\n type ProviderReaderRuntimeCredentialsResolverOptions,\n type ProviderReaderRuntimeErrorCode,\n type ProviderReaderRuntimeHandler,\n type ProviderReaderRuntimeImplementation,\n type ProviderReaderRuntimeItem,\n type ProviderReaderRuntimeOptions,\n type ProviderReaderRuntimeResponse,\n type WorkspaceConnectionCapability,\n type WorkspaceConnectionCredentialKey,\n type WorkspaceConnectionProvider,\n type WorkspaceConnectionProviderId,\n type WorkspaceConnectionTemplateUse,\n} from \"./connections/index.js\";\n\n// Scripts\nexport {\n runScript,\n loadEnv,\n parseArgs,\n camelCaseArgs,\n isValidPath,\n isValidProjectPath,\n ensureDir,\n fail,\n} from \"./scripts/index.js\";\n\n// Secrets registry — import from \"@agent-native/core/secrets\" when possible\n// (the subpath keeps the top-level entry point lean), but re-export the\n// public API here for convenience.\nexport {\n registerRequiredSecret,\n listRequiredSecrets,\n getRequiredSecret,\n readAppSecret,\n writeAppSecret,\n deleteAppSecret,\n type RegisteredSecret,\n type SecretScope,\n type SecretKind,\n type SecretValidator,\n type SecretRef,\n} from \"./secrets/index.js\";\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,mCAAmC;AACnC,+CAA+C;AAE/C,0BAA0B;AAC1B,OAAO,EACL,4BAA4B,EAU5B,aAAa,GACd,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EACL,YAAY,EACZ,oBAAoB,EACpB,sBAAsB,EAMtB,oBAAoB,EACpB,iBAAiB,EACjB,6BAA6B,GAO9B,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AACjE,OAAO,EACL,qBAAqB,EACrB,sBAAsB,GAEvB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EACL,+BAA+B,EAC/B,wBAAwB,GAEzB,MAAM,sBAAsB,CAAC;AAE9B,SAA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,MAAM,kCAAkC,CAAC;AAE1C,iDAAiD;AACjD,OAAO,EACL,gBAAgB,EAChB,0BAA0B,EAC1B,8BAA8B,EAC9B,2BAA2B,EAC3B,oBAAoB,EACpB,kCAAkC,EAClC,iCAAiC,EACjC,iBAAiB,EACjB,8BAA8B,EAC9B,+BAA+B,EAC/B,mBAAmB,EACnB,gCAAgC,EAChC,6CAA6C,EAC7C,2CAA2C,EAC3C,sBAAsB,EACtB,mCAAmC,GA2BpC,MAAM,wBAAwB,CAAC;AAEhC,UAAU;AACV,OAAO,EACL,SAAS,EACT,OAAO,EACP,SAAS,EACT,aAAa,EACb,WAAW,EACX,kBAAkB,EAClB,SAAS,EACT,IAAI,GACL,MAAM,oBAAoB,CAAC;AAE5B,4EAA4E;AAC5E,wEAAwE;AACxE,mCAAmC;AACnC,OAAO,EACL,sBAAsB,EACtB,mBAAmB,EACnB,iBAAiB,EACjB,aAAa,EACb,cAAc,EACd,eAAe,GAMhB,MAAM,oBAAoB,CAAC","sourcesContent":["// Framework for agent-native apps.\n// Import everything from \"@agent-native/core\".\n\n// Agent (production mode)\nexport {\n createProductionAgentHandler,\n type ActionEntry,\n type ScriptEntry,\n type ProductionAgentOptions,\n type ActionTool,\n type ScriptTool,\n type AgentMessage,\n type AgentChatRequest,\n type AgentChatEvent,\n type AgentChatAttachment,\n DEFAULT_MODEL,\n} from \"./agent/index.js\";\nexport {\n defineAction,\n AgentActionStopError,\n isAgentActionStopError,\n type ActionHttpConfig,\n type AgentActionStopOptions,\n type PublicAgentActionConfig,\n type ActionDeepLink,\n type ActionLinkBuilder,\n MCP_APP_EXTENSION_ID,\n MCP_APP_MIME_TYPE,\n MCP_APP_RESOURCE_URI_META_KEY,\n type ActionMcpAppConfig,\n type ActionMcpAppCsp,\n type ActionMcpAppHtmlBuilder,\n type ActionMcpAppPermissions,\n type ActionMcpAppResourceConfig,\n type ActionMcpAppResourceMeta,\n} from \"./action.js\";\nexport { createDevScriptRegistry } from \"./scripts/dev/index.js\";\nexport {\n createAgentChatPlugin,\n defaultAgentChatPlugin,\n type AgentChatPluginOptions,\n} from \"./server/agent-chat-plugin.js\";\nexport {\n createAgentNativeEmbeddedPlugin,\n mountAgentNativeEmbedded,\n type AgentNativeEmbeddedPluginOptions,\n} from \"./server/embedded.js\";\n\n// Server\nexport {\n createServer,\n createSSEHandler,\n defineNitroPlugin,\n autoMountAuth,\n getSession,\n type CreateServerOptions,\n type SSEHandlerOptions,\n type AuthSession,\n type AuthOptions,\n} from \"./server/index.js\";\n\n// Client\nexport {\n sendToAgentChat,\n useAgentChatGenerating,\n useDevMode,\n useSendToAgentChat,\n CodeRequiredDialog,\n useAgentNativeEmbeddedBrowserSession,\n useDbSync,\n useFileWatcher,\n cn,\n ApiKeySettings,\n useSession,\n AgentNativeEmbedded,\n useProductionAgent,\n ProductionAgentPanel,\n type AgentChatMessage,\n type AgentNativeEmbeddedProps,\n type UseAgentNativeEmbeddedBrowserSessionOptions,\n type CodeRequiredDialogProps,\n type ProductionAgentMessage,\n type UseProductionAgentResult,\n type ProductionAgentPanelProps,\n useActionQuery,\n useActionMutation,\n} from \"./client/index.js\";\n\n// Shared (isomorphic)\nexport {\n agentChat,\n type AgentChatCallOptions,\n type AgentChatResponse,\n} from \"./shared/index.js\";\n\n// Agent Web surfaces\nexport {\n AGENT_WEB_CRAWLER_CATEGORIES,\n AGENT_WEB_CRAWLER_USER_AGENTS,\n DEFAULT_AGENT_WEB_CRAWLER_POLICY,\n absoluteUrl,\n agentWebConfigFromPackageJson,\n buildAgentWebStaticFiles,\n buildBaseJsonLd,\n buildLlmsFullTxt,\n buildLlmsTxt,\n buildMarkdownResponseHeaders,\n buildPageJsonLd,\n buildRobotsTxt,\n buildSitemapXml,\n deriveAgentWebPublicRoutes,\n estimateMarkdownTokens,\n markdownFilePathForPage,\n markdownUrlForPage,\n normalizeAgentWebConfig,\n pathPatternMatches,\n resolveAgentWebCrawlerPolicy,\n type AgentWebConfig,\n type AgentWebCrawlerCategory,\n type AgentWebCrawlerDecision,\n type AgentWebCrawlerOverrides,\n type AgentWebCrawlerPolicy,\n type AgentWebInputConfig,\n type AgentWebPage,\n type AgentWebStaticFile,\n type BuildAgentWebStaticFilesOptions,\n type DeriveAgentWebPublicRoutesOptions,\n type MarkdownResponseHeadersOptions,\n} from \"./agent-web/index.js\";\n\n// Token usage tracking\nexport {\n recordUsage,\n getUsageSummary,\n getUserUsageCents,\n calculateCost,\n usageBillingForEngine,\n builderCreditsFromCostCents,\n BUILDER_AGENT_CREDIT_MARGIN_MULTIPLIER,\n BUILDER_AGENT_CREDITS_PER_USD,\n BUILDER_CREDIT_USAGE_BILLING,\n USD_USAGE_BILLING,\n type UsageRecord,\n type UsageSummary,\n type UsageBillingMode,\n type UsageBillingUnit,\n type UsageBucket,\n type DailyBucket,\n type UsageRecentEntry,\n} from \"./usage/store.js\";\n\n// Workspace-scoped third-party connection metadata\nexport {\n deleteWorkspaceConnection,\n getWorkspaceConnectionAppAccess,\n getWorkspaceConnection,\n getWorkspaceConnectionGrant,\n listWorkspaceConnectionProviderCatalogForApp,\n listWorkspaceConnectionGrants,\n listWorkspaceConnections,\n resolveWorkspaceConnectionCredentialForApp,\n resolveWorkspaceConnectionCredentialsForApp,\n revokeWorkspaceConnectionGrant,\n serializeWorkspaceConnectionGrant,\n serializeWorkspaceConnection,\n summarizeWorkspaceConnectionProviderForApp,\n summarizeWorkspaceConnectionProviderReadiness,\n upsertWorkspaceConnectionGrant,\n upsertWorkspaceConnection,\n type ListWorkspaceConnectionProviderCatalogForAppOptions,\n type ListWorkspaceConnectionGrantsOptions,\n type ListWorkspaceConnectionsOptions,\n type ResolveWorkspaceConnectionCredentialForAppOptions,\n type ResolveWorkspaceConnectionCredentialsForAppOptions,\n type SerializedWorkspaceConnectionGrant,\n type SerializedWorkspaceConnection,\n type SummarizeWorkspaceConnectionProviderForAppOptions,\n type SummarizeWorkspaceConnectionProviderReadinessOptions,\n type UpsertWorkspaceConnectionGrantInput,\n type UpsertWorkspaceConnectionInput,\n type WorkspaceConnectionAppAccess,\n type WorkspaceConnectionAppAccessMode,\n type WorkspaceConnection,\n type WorkspaceConnectionCredentialBackend,\n type WorkspaceConnectionCredentialProvenance,\n type WorkspaceConnectionCredentialRef,\n type WorkspaceConnectionCredentialResolution,\n type WorkspaceConnectionCredentialResolutionCheck,\n type WorkspaceConnectionCredentialResolutionStatus,\n type WorkspaceConnectionCredentialsResolution,\n type WorkspaceConnectionExplicitGrantSummary,\n type WorkspaceConnectionForAppSummary,\n type WorkspaceConnectionGrant,\n type WorkspaceConnectionGrantAvailability,\n type WorkspaceConnectionGrantState,\n type WorkspaceConnectionProviderAppSummary,\n type WorkspaceConnectionProviderLike,\n type WorkspaceConnectionProviderCatalogForApp,\n type WorkspaceConnectionProviderCatalogForAppItem,\n type WorkspaceConnectionProviderReadiness,\n type WorkspaceConnectionProviderReadinessStatus,\n type WorkspaceConnectionPublicCredentialRef,\n type WorkspaceConnectionStatus,\n workspaceConnectionIsAvailableToApp,\n} from \"./workspace-connections/index.js\";\n\n// Reusable workspace connection provider catalog\nexport {\n PROVIDER_READERS,\n ProviderReaderRuntimeError,\n WORKSPACE_CONNECTION_PROVIDERS,\n createProviderReaderRuntime,\n defineProviderReader,\n defineProviderReaderImplementation,\n defineWorkspaceConnectionProvider,\n getProviderReader,\n getWorkspaceConnectionProvider,\n isWorkspaceConnectionProviderId,\n listProviderReaders,\n listWorkspaceConnectionProviders,\n listWorkspaceConnectionProvidersForCapability,\n listWorkspaceConnectionProvidersForTemplate,\n providerReaderSupports,\n workspaceConnectionProviderSupports,\n type ListWorkspaceConnectionProvidersOptions,\n type ListProviderReadersOptions,\n type ProviderReaderCapability,\n type ProviderReaderCredentialRequirement,\n type ProviderReaderDefinition,\n type ProviderReaderImplementationStatus,\n type ProviderReaderOperation,\n type ProviderReaderOperationDescriptor,\n type ProviderReaderOperationParameter,\n type ProviderReaderRequest,\n type ProviderReaderRuntime,\n type ProviderReaderRuntimeConnection,\n type ProviderReaderRuntimeConnectionResolverOptions,\n type ProviderReaderRuntimeContext,\n type ProviderReaderRuntimeCredentialsResolverOptions,\n type ProviderReaderRuntimeErrorCode,\n type ProviderReaderRuntimeHandler,\n type ProviderReaderRuntimeImplementation,\n type ProviderReaderRuntimeItem,\n type ProviderReaderRuntimeOptions,\n type ProviderReaderRuntimeResponse,\n type WorkspaceConnectionCapability,\n type WorkspaceConnectionCredentialKey,\n type WorkspaceConnectionProvider,\n type WorkspaceConnectionProviderId,\n type WorkspaceConnectionTemplateUse,\n} from \"./connections/index.js\";\n\n// Scripts\nexport {\n runScript,\n loadEnv,\n parseArgs,\n camelCaseArgs,\n isValidPath,\n isValidProjectPath,\n ensureDir,\n fail,\n} from \"./scripts/index.js\";\n\n// Secrets registry — import from \"@agent-native/core/secrets\" when possible\n// (the subpath keeps the top-level entry point lean), but re-export the\n// public API here for convenience.\nexport {\n registerRequiredSecret,\n listRequiredSecrets,\n getRequiredSecret,\n readAppSecret,\n writeAppSecret,\n deleteAppSecret,\n type RegisteredSecret,\n type SecretScope,\n type SecretKind,\n type SecretValidator,\n type SecretRef,\n} from \"./secrets/index.js\";\n"]}
|
|
@@ -71,6 +71,8 @@ export interface MCPConfig {
|
|
|
71
71
|
export interface MCPCallerIdentity {
|
|
72
72
|
userEmail: string | undefined;
|
|
73
73
|
orgDomain: string | undefined;
|
|
74
|
+
/** Present only for standard remote MCP OAuth access tokens. */
|
|
75
|
+
oauthScopes?: string[];
|
|
74
76
|
}
|
|
75
77
|
/** Per-request context used to turn an action's relative deep link into the
|
|
76
78
|
* absolute web URL (and desktop `agentnative://` URL) the external agent
|
|
@@ -168,6 +170,7 @@ export declare function getAccessTokens(): string[];
|
|
|
168
170
|
*/
|
|
169
171
|
export declare function verifyAuth(authHeader: string | undefined, ownerEmailHeader?: string | undefined, options?: {
|
|
170
172
|
allowDevOpen?: boolean;
|
|
173
|
+
resourceUrl?: string;
|
|
171
174
|
}): Promise<{
|
|
172
175
|
authed: boolean;
|
|
173
176
|
identity?: MCPCallerIdentity;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build-server.d.ts","sourceRoot":"","sources":["../../src/mcp/build-server.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAC;
|
|
1
|
+
{"version":3,"file":"build-server.d.ts","sourceRoot":"","sources":["../../src/mcp/build-server.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAC;AAsBhE,MAAM,WAAW,SAAS;IACxB,wCAAwC;IACxC,IAAI,EAAE,MAAM,CAAC;IACb;;;;;;;OAOG;IACH,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,sBAAsB;IACtB,WAAW,EAAE,MAAM,CAAC;IACpB,uCAAuC;IACvC,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,mDAAmD;IACnD,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC;IACrC;;;;;;;;;;;OAWG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC;IAChD,qEAAqE;IACrE,QAAQ,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC;IAChD;;;;;;OAMG;IACH,oBAAoB,CAAC,EAAE,OAAO,CAAC;CAChC;AAED;;;;;;;GAOG;AACH,MAAM,WAAW,iBAAiB;IAChC,SAAS,EAAE,MAAM,GAAG,SAAS,CAAC;IAC9B,SAAS,EAAE,MAAM,GAAG,SAAS,CAAC;IAC9B,gEAAgE;IAChE,WAAW,CAAC,EAAE,MAAM,EAAE,CAAC;CACxB;AAED;;;kEAGkE;AAClE,MAAM,WAAW,cAAc;IAC7B,+DAA+D;IAC/D,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,yEAAyE;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server.js
CHANGED
|
@@ -17,11 +17,20 @@
|
|
|
17
17
|
* Node-only at the SDK level, but this module itself has no Node-only imports
|
|
18
18
|
* — it can be bundled into the serverless function alongside `mountMCP`.
|
|
19
19
|
*/
|
|
20
|
+
import { isMcpActionResult } from "../mcp-client/app-result.js";
|
|
21
|
+
import { MCP_APP_EXTENSION_ID, MCP_APP_MIME_TYPE, MCP_APP_RESOURCE_URI_META_KEY, } from "../action.js";
|
|
20
22
|
import { runWithRequestContext } from "../server/request-context.js";
|
|
21
23
|
import { toAbsoluteOpenUrl, toDesktopOpenUrl } from "../server/deep-link.js";
|
|
22
24
|
import { isAgentNativeOpenDeepLink, withCollapsedAgentSidebarParam, } from "../shared/agent-sidebar-url.js";
|
|
23
25
|
import { getBuiltinCrossAppTools } from "./builtin-tools.js";
|
|
24
26
|
import { MCP_CONNECT_SCOPE } from "./connect-store.js";
|
|
27
|
+
import { hasMcpOAuthScope, verifyMcpOAuthAccessToken, } from "./oauth-token.js";
|
|
28
|
+
function isActionVisibleForOAuthScope(entry, scopes) {
|
|
29
|
+
if (!scopes)
|
|
30
|
+
return true;
|
|
31
|
+
const required = entry.readOnly === true ? "mcp:read" : "mcp:write";
|
|
32
|
+
return hasMcpOAuthScope(scopes, required);
|
|
33
|
+
}
|
|
25
34
|
/**
|
|
26
35
|
* Build the deep-link content block + structured `_meta` for a tool result.
|
|
27
36
|
* Best-effort: any throw / nullish link is swallowed so a bad `link` builder
|
|
@@ -77,6 +86,76 @@ function mergeBuiltinTools(config, baseActions, requestMeta) {
|
|
|
77
86
|
}
|
|
78
87
|
return merged;
|
|
79
88
|
}
|
|
89
|
+
function safeUiSegment(value, fallback) {
|
|
90
|
+
const normalized = (value || fallback)
|
|
91
|
+
.trim()
|
|
92
|
+
.toLowerCase()
|
|
93
|
+
.replace(/[^a-z0-9._-]+/g, "-")
|
|
94
|
+
.replace(/^-+|-+$/g, "");
|
|
95
|
+
return normalized || fallback;
|
|
96
|
+
}
|
|
97
|
+
function defaultMcpAppUri(config, actionName) {
|
|
98
|
+
const app = safeUiSegment(config.appId ?? config.name, "agent-native");
|
|
99
|
+
const action = safeUiSegment(actionName, "tool");
|
|
100
|
+
return `ui://${app}/${action}`;
|
|
101
|
+
}
|
|
102
|
+
function mcpAppUiMeta(resource) {
|
|
103
|
+
const base = resource._meta && typeof resource._meta === "object"
|
|
104
|
+
? { ...resource._meta }
|
|
105
|
+
: {};
|
|
106
|
+
const existingUi = base.ui && typeof base.ui === "object" && !Array.isArray(base.ui)
|
|
107
|
+
? base.ui
|
|
108
|
+
: {};
|
|
109
|
+
const ui = { ...existingUi };
|
|
110
|
+
if (resource.csp)
|
|
111
|
+
ui.csp = resource.csp;
|
|
112
|
+
if (resource.permissions)
|
|
113
|
+
ui.permissions = resource.permissions;
|
|
114
|
+
if (resource.domain)
|
|
115
|
+
ui.domain = resource.domain;
|
|
116
|
+
if (typeof resource.prefersBorder === "boolean") {
|
|
117
|
+
ui.prefersBorder = resource.prefersBorder;
|
|
118
|
+
}
|
|
119
|
+
if (Object.keys(ui).length > 0)
|
|
120
|
+
base.ui = ui;
|
|
121
|
+
return Object.keys(base).length > 0 ? base : undefined;
|
|
122
|
+
}
|
|
123
|
+
function resolveMcpAppResource(config, actionName, entry) {
|
|
124
|
+
const resource = entry.mcpApp?.resource;
|
|
125
|
+
if (!resource)
|
|
126
|
+
return null;
|
|
127
|
+
const uri = resource.uri?.trim() || defaultMcpAppUri(config, actionName);
|
|
128
|
+
if (!uri.startsWith("ui://"))
|
|
129
|
+
return null;
|
|
130
|
+
const resourceMeta = mcpAppUiMeta(resource);
|
|
131
|
+
return {
|
|
132
|
+
uri,
|
|
133
|
+
name: resource.name?.trim() || actionName,
|
|
134
|
+
...(resource.title ? { title: resource.title } : {}),
|
|
135
|
+
...((resource.description ?? entry.tool.description)
|
|
136
|
+
? { description: resource.description ?? entry.tool.description }
|
|
137
|
+
: {}),
|
|
138
|
+
html: resource.html,
|
|
139
|
+
mimeType: resource.mimeType ?? MCP_APP_MIME_TYPE,
|
|
140
|
+
...(resourceMeta ? { _meta: resourceMeta } : {}),
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
function getMcpAppResources(config, actions) {
|
|
144
|
+
return Object.entries(actions).flatMap(([name, entry]) => {
|
|
145
|
+
const resource = resolveMcpAppResource(config, name, entry);
|
|
146
|
+
return resource ? [resource] : [];
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
function renderMcpAppHtml(resource, actionName, config, requestMeta) {
|
|
150
|
+
if (typeof resource.html === "function") {
|
|
151
|
+
return resource.html({
|
|
152
|
+
actionName,
|
|
153
|
+
appId: config.appId,
|
|
154
|
+
requestOrigin: requestMeta?.origin,
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
return resource.html;
|
|
158
|
+
}
|
|
80
159
|
// ---------------------------------------------------------------------------
|
|
81
160
|
// MCP Server creation — converts ActionEntry registry to MCP tools
|
|
82
161
|
// ---------------------------------------------------------------------------
|
|
@@ -90,8 +169,7 @@ function mergeBuiltinTools(config, baseActions, requestMeta) {
|
|
|
90
169
|
*/
|
|
91
170
|
export async function createMCPServerForRequest(config, identity, requestMeta) {
|
|
92
171
|
const { Server } = await import("@modelcontextprotocol/sdk/server/index.js");
|
|
93
|
-
const { ListToolsRequestSchema, CallToolRequestSchema } = await import("@modelcontextprotocol/sdk/types.js");
|
|
94
|
-
const server = new Server({ name: config.name, version: config.version ?? "1.0.0" }, { capabilities: { tools: {} } });
|
|
172
|
+
const { ListToolsRequestSchema, CallToolRequestSchema, ListResourcesRequestSchema, ReadResourceRequestSchema, ListResourceTemplatesRequestSchema, } = await import("@modelcontextprotocol/sdk/types.js");
|
|
95
173
|
// Resolve the effective caller identity. JWT / header-derived identity
|
|
96
174
|
// (passed by `mountMCP` via `verifyAuth`) wins. When the caller passed no
|
|
97
175
|
// identity — the stdio **standalone** path — fall back to the
|
|
@@ -118,6 +196,26 @@ export async function createMCPServerForRequest(config, identity, requestMeta) {
|
|
|
118
196
|
? config.productionActions
|
|
119
197
|
: config.actions;
|
|
120
198
|
const actions = mergeBuiltinTools(config, baseActions, requestMeta);
|
|
199
|
+
const visibleActions = Object.fromEntries(Object.entries(actions).filter(([, entry]) => isActionVisibleForOAuthScope(entry, effectiveIdentity?.oauthScopes)));
|
|
200
|
+
const mcpAppResources = hasMcpOAuthScope(effectiveIdentity?.oauthScopes, "mcp:apps")
|
|
201
|
+
? getMcpAppResources(config, visibleActions)
|
|
202
|
+
: [];
|
|
203
|
+
const supportsMcpApps = mcpAppResources.length > 0;
|
|
204
|
+
const server = new Server({ name: config.name, version: config.version ?? "1.0.0" }, {
|
|
205
|
+
capabilities: {
|
|
206
|
+
tools: {},
|
|
207
|
+
...(supportsMcpApps
|
|
208
|
+
? {
|
|
209
|
+
resources: {},
|
|
210
|
+
extensions: {
|
|
211
|
+
[MCP_APP_EXTENSION_ID]: {
|
|
212
|
+
mimeTypes: [MCP_APP_MIME_TYPE],
|
|
213
|
+
},
|
|
214
|
+
},
|
|
215
|
+
}
|
|
216
|
+
: {}),
|
|
217
|
+
},
|
|
218
|
+
});
|
|
121
219
|
// Resolve orgId once per request (DB lookup) so subsequent wraps are
|
|
122
220
|
// synchronous. The caller identity may be undefined for true dev-open —
|
|
123
221
|
// in that case we run with no userEmail/orgId, which makes downstream
|
|
@@ -148,8 +246,9 @@ export async function createMCPServerForRequest(config, identity, requestMeta) {
|
|
|
148
246
|
// applies to the listing too.
|
|
149
247
|
server.setRequestHandler(ListToolsRequestSchema, async () => {
|
|
150
248
|
return withCallerContext(async () => {
|
|
151
|
-
const tools = Object.entries(
|
|
249
|
+
const tools = Object.entries(visibleActions).map(([name, entry]) => {
|
|
152
250
|
const hasLink = typeof entry.link === "function";
|
|
251
|
+
const mcpAppResource = resolveMcpAppResource(config, name, entry);
|
|
153
252
|
const baseDescription = entry.tool.description ?? name;
|
|
154
253
|
return {
|
|
155
254
|
name,
|
|
@@ -160,12 +259,24 @@ export async function createMCPServerForRequest(config, identity, requestMeta) {
|
|
|
160
259
|
type: "object",
|
|
161
260
|
properties: {},
|
|
162
261
|
},
|
|
262
|
+
...(mcpAppResource
|
|
263
|
+
? {
|
|
264
|
+
_meta: {
|
|
265
|
+
[MCP_APP_RESOURCE_URI_META_KEY]: mcpAppResource.uri,
|
|
266
|
+
ui: {
|
|
267
|
+
resourceUri: mcpAppResource.uri,
|
|
268
|
+
visibility: entry.mcpApp?.visibility ?? ["model", "app"],
|
|
269
|
+
},
|
|
270
|
+
},
|
|
271
|
+
}
|
|
272
|
+
: {}),
|
|
163
273
|
...(hasLink
|
|
164
274
|
? { annotations: { "agent-native/producesOpenLink": true } }
|
|
165
275
|
: {}),
|
|
166
276
|
};
|
|
167
277
|
});
|
|
168
|
-
if (config.askAgent
|
|
278
|
+
if (config.askAgent &&
|
|
279
|
+
hasMcpOAuthScope(effectiveIdentity?.oauthScopes, "mcp:write")) {
|
|
169
280
|
tools.push({
|
|
170
281
|
name: "ask-agent",
|
|
171
282
|
description: "Send a natural-language message to the app's AI agent and get a response. " +
|
|
@@ -193,6 +304,17 @@ export async function createMCPServerForRequest(config, identity, requestMeta) {
|
|
|
193
304
|
return withCallerContext(async () => {
|
|
194
305
|
const { name, arguments: args } = request.params;
|
|
195
306
|
if (name === "ask-agent" && config.askAgent) {
|
|
307
|
+
if (!hasMcpOAuthScope(effectiveIdentity?.oauthScopes, "mcp:write")) {
|
|
308
|
+
return {
|
|
309
|
+
content: [
|
|
310
|
+
{
|
|
311
|
+
type: "text",
|
|
312
|
+
text: "Forbidden: OAuth scope does not allow ask-agent",
|
|
313
|
+
},
|
|
314
|
+
],
|
|
315
|
+
isError: true,
|
|
316
|
+
};
|
|
317
|
+
}
|
|
196
318
|
const message = args?.message ?? "";
|
|
197
319
|
try {
|
|
198
320
|
const result = await config.askAgent(message);
|
|
@@ -212,11 +334,27 @@ export async function createMCPServerForRequest(config, identity, requestMeta) {
|
|
|
212
334
|
isError: true,
|
|
213
335
|
};
|
|
214
336
|
}
|
|
337
|
+
if (!isActionVisibleForOAuthScope(entry, effectiveIdentity?.oauthScopes)) {
|
|
338
|
+
return {
|
|
339
|
+
content: [
|
|
340
|
+
{
|
|
341
|
+
type: "text",
|
|
342
|
+
text: `Forbidden: OAuth scope does not allow tool ${name}`,
|
|
343
|
+
},
|
|
344
|
+
],
|
|
345
|
+
isError: true,
|
|
346
|
+
};
|
|
347
|
+
}
|
|
215
348
|
try {
|
|
216
349
|
const result = await entry.run(args ?? {});
|
|
217
|
-
const
|
|
350
|
+
const resultForClient = isMcpActionResult(result)
|
|
351
|
+
? result.text
|
|
352
|
+
: result;
|
|
353
|
+
const text = typeof resultForClient === "string"
|
|
354
|
+
? resultForClient
|
|
355
|
+
: JSON.stringify(resultForClient);
|
|
218
356
|
const content = [{ type: "text", text }];
|
|
219
|
-
const { block, _meta } = buildLinkArtifacts(entry, args ?? {}, result, requestMeta);
|
|
357
|
+
const { block, _meta } = buildLinkArtifacts(entry, args ?? {}, isMcpActionResult(result) ? result.raw : result, requestMeta);
|
|
220
358
|
if (block)
|
|
221
359
|
content.push(block);
|
|
222
360
|
return { content, ...(_meta ? { _meta } : {}) };
|
|
@@ -229,6 +367,51 @@ export async function createMCPServerForRequest(config, identity, requestMeta) {
|
|
|
229
367
|
}
|
|
230
368
|
});
|
|
231
369
|
});
|
|
370
|
+
if (supportsMcpApps) {
|
|
371
|
+
server.setRequestHandler(ListResourcesRequestSchema, async () => {
|
|
372
|
+
return withCallerContext(async () => ({
|
|
373
|
+
resources: mcpAppResources.map((resource) => ({
|
|
374
|
+
uri: resource.uri,
|
|
375
|
+
name: resource.name,
|
|
376
|
+
...(resource.title ? { title: resource.title } : {}),
|
|
377
|
+
...(resource.description
|
|
378
|
+
? { description: resource.description }
|
|
379
|
+
: {}),
|
|
380
|
+
mimeType: resource.mimeType,
|
|
381
|
+
...(resource._meta ? { _meta: resource._meta } : {}),
|
|
382
|
+
})),
|
|
383
|
+
}));
|
|
384
|
+
});
|
|
385
|
+
server.setRequestHandler(ListResourceTemplatesRequestSchema, async () => {
|
|
386
|
+
return { resourceTemplates: [] };
|
|
387
|
+
});
|
|
388
|
+
server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
|
|
389
|
+
return withCallerContext(async () => {
|
|
390
|
+
const uri = request.params?.uri;
|
|
391
|
+
const found = Object.entries(visibleActions)
|
|
392
|
+
.map(([name, entry]) => ({
|
|
393
|
+
actionName: name,
|
|
394
|
+
resource: resolveMcpAppResource(config, name, entry),
|
|
395
|
+
}))
|
|
396
|
+
.find((candidate) => candidate.resource?.uri === uri);
|
|
397
|
+
if (!found?.resource) {
|
|
398
|
+
throw new Error(`MCP App resource not found: ${uri}`);
|
|
399
|
+
}
|
|
400
|
+
return {
|
|
401
|
+
contents: [
|
|
402
|
+
{
|
|
403
|
+
uri: found.resource.uri,
|
|
404
|
+
mimeType: found.resource.mimeType,
|
|
405
|
+
text: renderMcpAppHtml(found.resource, found.actionName, config, requestMeta),
|
|
406
|
+
...(found.resource._meta
|
|
407
|
+
? { _meta: found.resource._meta }
|
|
408
|
+
: {}),
|
|
409
|
+
},
|
|
410
|
+
],
|
|
411
|
+
};
|
|
412
|
+
});
|
|
413
|
+
});
|
|
414
|
+
}
|
|
232
415
|
return server;
|
|
233
416
|
}
|
|
234
417
|
// ---------------------------------------------------------------------------
|
|
@@ -311,6 +494,23 @@ export async function verifyAuth(authHeader, ownerEmailHeader, options = {}) {
|
|
|
311
494
|
// owner hint there so the local install/connect flow stays tenant-scoped.
|
|
312
495
|
const accessTokens = getAccessTokens();
|
|
313
496
|
const hasA2ASecret = !!process.env.A2A_SECRET;
|
|
497
|
+
const token = authHeader?.startsWith("Bearer ")
|
|
498
|
+
? authHeader.slice(7)
|
|
499
|
+
: undefined;
|
|
500
|
+
if (token) {
|
|
501
|
+
const oauthIdentity = await verifyMcpOAuthAccessToken(token, options.resourceUrl);
|
|
502
|
+
if (oauthIdentity) {
|
|
503
|
+
return {
|
|
504
|
+
authed: true,
|
|
505
|
+
identity: {
|
|
506
|
+
userEmail: oauthIdentity.userEmail,
|
|
507
|
+
orgDomain: oauthIdentity.orgDomain,
|
|
508
|
+
oauthScopes: oauthIdentity.scopes,
|
|
509
|
+
},
|
|
510
|
+
fullSurface: true,
|
|
511
|
+
};
|
|
512
|
+
}
|
|
513
|
+
}
|
|
314
514
|
if (accessTokens.length === 0 && !hasA2ASecret) {
|
|
315
515
|
if (options.allowDevOpen === false) {
|
|
316
516
|
return { authed: false };
|
|
@@ -325,9 +525,8 @@ export async function verifyAuth(authHeader, ownerEmailHeader, options = {}) {
|
|
|
325
525
|
fullSurface: !!(ownerEmailHeader && ownerEmailHeader.trim()),
|
|
326
526
|
};
|
|
327
527
|
}
|
|
328
|
-
if (!
|
|
528
|
+
if (!token)
|
|
329
529
|
return { authed: false };
|
|
330
|
-
const token = authHeader.slice(7);
|
|
331
530
|
// Try JWT via A2A_SECRET
|
|
332
531
|
if (hasA2ASecret) {
|
|
333
532
|
try {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build-server.js","sourceRoot":"","sources":["../../src/mcp/build-server.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAGH,OAAO,EAAE,qBAAqB,EAAE,MAAM,8BAA8B,CAAC;AACrE,OAAO,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC7E,OAAO,EACL,yBAAyB,EACzB,8BAA8B,GAC/B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,uBAAuB,EAAE,MAAM,oBAAoB,CAAC;AAC7D,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AA8EvD;;;;GAIG;AACH,MAAM,UAAU,kBAAkB,CAChC,KAAkB,EAClB,IAAyB,EACzB,MAAW,EACX,IAAgC;IAKhC,IAAI,OAAO,KAAK,CAAC,IAAI,KAAK,UAAU;QAAE,OAAO,EAAE,CAAC;IAChD,IAAI,CAAC;QACH,MAAM,EAAE,GAAG,KA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;gBACD,mEAAmE;gBACnE,WAAW,EAAE,IAAI;aAClB,CAAC;QACJ,CAAC;QAAC,MAAM,CAAC;YACP,gDAAgD;QAClD,CAAC;IACH,CAAC;IAED,uEAAuE;IACvE,uEAAuE;IACvE,4DAA4D;IAC5D,IAAI,YAAY,CAAC,MAAM,GAAG,CAAC,IAAI,YAAY,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;QAC5D,OAAO;YACL,MAAM,EAAE,IAAI;YACZ,QAAQ,EAAE,yBAAyB,CAAC,gBAAgB,CAAC;YACrD,qDAAqD;YACrD,WAAW,EAAE,IAAI;SAClB,CAAC;IACJ,CAAC;IAED,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC;AAC3B,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,sBAAsB,CAC1C,SAA6B;IAE7B,IAAI,CAAC,SAAS;QAAE,OAAO,SAAS,CAAC;IACjC,IAAI,CAAC;QACH,MAAM,EAAE,kBAAkB,EAAE,GAAG,MAAM,MAAM,CAAC,mBAAmB,CAAC,CAAC;QACjE,MAAM,GAAG,GAAG,MAAM,kBAAkB,CAAC,SAAS,CAAC,CAAC;QAChD,OAAO,GAAG,EAAE,KAAK,IAAI,SAAS,CAAC;IACjC,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,SAAS,CAAC;IACnB,CAAC;AACH,CAAC","sourcesContent":["/**\n * Shared MCP server builder.\n *\n * Extracted from `server.ts` so the stateless Streamable-HTTP mount\n * (`mountMCP`) and the stdio transport (`runMCPStdio --standalone`) build the\n * *same* MCP server from the *same* `ActionEntry` registry. Both surfaces:\n *\n * - expose every action as an MCP tool (+ the `ask-agent` meta-tool),\n * - append the framework deep-link block / `_meta` to every tool result,\n * - wrap `run()` / `askAgent()` in `runWithRequestContext` so per-user /\n * per-org scoping (accessFilter, resolveCredential, MCP visibility) is\n * honoured.\n *\n * `server.ts` re-exports `createMCPServerForRequest` and the auth helpers so\n * any (future) external importer of `@agent-native/core/mcp` keeps resolving.\n *\n * Node-only at the SDK level, but this module itself has no Node-only imports\n * — it can be bundled into the serverless function alongside `mountMCP`.\n */\n\nimport type { ActionEntry } from \"../agent/production-agent.js\";\nimport { runWithRequestContext } from \"../server/request-context.js\";\nimport { toAbsoluteOpenUrl, toDesktopOpenUrl } from \"../server/deep-link.js\";\nimport {\n isAgentNativeOpenDeepLink,\n withCollapsedAgentSidebarParam,\n} from \"../shared/agent-sidebar-url.js\";\nimport { getBuiltinCrossAppTools } from \"./builtin-tools.js\";\nimport { MCP_CONNECT_SCOPE } from \"./connect-store.js\";\n\nexport interface MCPConfig {\n /** App name shown in MCP server info */\n name: string;\n /**\n * Canonical app id (directory under `apps/`, e.g. `mail`) this MCP server\n * is mounted for. Optional & back-compat: when omitted the builtin\n * cross-app tools fall back to lowercasing `name`. Used by `open_app` /\n * `ask_app` / `create_workspace_app` to tell \"this app\" from a cross-app\n * target so they resolve the *target* app's origin rather than echoing the\n * current request origin.\n */\n appId?: string;\n /** App description */\n description: string;\n /** Version string (default \"1.0.0\") */\n version?: string;\n /** Action registry — same as agent chat and A2A */\n actions: Record<string, ActionEntry>;\n /**\n * Full (\"production\") action surface served to an **authenticated real\n * caller** — a connect-minted token, an `agent-native mcp install` stdio\n * proxy (owner-email header / `AGENT_NATIVE_OWNER_EMAIL`), or a deployed /\n * `AGENT_MODE=production` app. In local dev `actions` is intentionally the\n * sparse, dev-toggled surface (builtins + read-only public-agent actions)\n * so the local agent chat and unauthenticated dev probes don't see every\n * mutating tool; but per the external-agents contract a real caller that\n * connected with a token MUST get the full surface even in dev. When unset\n * (production, where `actions` already IS the full set) the swap is a\n * no-op. See `external-agents` skill, \"Dev vs production tool surface\".\n */\n productionActions?: Record<string, ActionEntry>;\n /** Handler for the ask-agent meta-tool — runs the full agent loop */\n askAgent?: (message: string) => Promise<string>;\n /**\n * Disable the generic cross-app builtin tools (`list_apps`, `open_app`,\n * `ask_app`, `create_workspace_app`, `list_templates`). They are merged in\n * by default so external agents get a stable verb set; a template action of\n * the same name always wins (template precedence). Set to `false` only for\n * a constrained / locked-down mount.\n */\n builtinCrossAppTools?: boolean;\n}\n\n/**\n * Identity extracted from a verified MCP bearer token / JWT. Used to wrap\n * `entry.run()` and `config.askAgent()` calls in `runWithRequestContext`\n * so downstream tools (db-query, accessFilter, resolveCredential) honour\n * per-user / per-org scoping. Without this wrap the MCP endpoint would\n * silently bypass tenant isolation. See finding #6 in\n * /tmp/security-audit/12-mcp-a2a-agent.md.\n */\nexport interface MCPCallerIdentity {\n userEmail: string | undefined;\n orgDomain: string | undefined;\n}\n\n/** Per-request context used to turn an action's relative deep link into the\n * absolute web URL (and desktop `agentnative://` URL) the external agent\n * surfaces. Derived from the inbound request headers in `mountMCP`, or from\n * the resolved local app origin in the stdio standalone path. */\nexport interface MCPRequestMeta {\n /** Origin of the running app, e.g. `http://localhost:8100`. */\n origin?: string;\n /** Optional client preference for which URL the *markdown* link uses. */\n target?: \"browser\" | \"desktop\" | \"terminal\";\n /**\n * The caller authenticated with a real credential (verified A2A/connect\n * JWT, matching ACCESS_TOKEN, or a forwarded owner-email header from\n * `agent-native mcp install`) — not the unauthenticated local dev-open\n * path. When true, `createMCPServerForRequest` serves\n * `config.productionActions` (the full surface) instead of the sparse dev\n * `config.actions`. Set by `mountMCP` from `verifyAuth`.\n */\n fullSurface?: boolean;\n}\n\n/**\n * Build the deep-link content block + structured `_meta` for a tool result.\n * Best-effort: any throw / nullish link is swallowed so a bad `link` builder\n * never fails the tool call.\n */\nexport function buildLinkArtifacts(\n entry: ActionEntry,\n args: Record<string, any>,\n result: any,\n meta: MCPRequestMeta | undefined,\n): {\n block?: { type: \"text\"; text: string };\n _meta?: Record<string, unknown>;\n} {\n if (typeof entry.link !== \"function\") return {};\n try {\n const lk = entry.link({ args: args ?? {}, result });\n if (!lk?.url) return {};\n const linkUrl = isAgentNativeOpenDeepLink(lk.url)\n ? withCollapsedAgentSidebarParam(lk.url)\n : lk.url;\n const webUrl = toAbsoluteOpenUrl(linkUrl, meta?.origin);\n const desktopUrl = toDesktopOpenUrl(linkUrl);\n const markdownUrl = meta?.target === \"desktop\" ? desktopUrl : webUrl;\n return {\n block: { type: \"text\", text: `\\n\\n[${lk.label} →](${markdownUrl})` },\n _meta: {\n \"agent-native/openLink\": {\n label: lk.label,\n view: lk.view,\n webUrl,\n desktopUrl,\n },\n },\n };\n } catch {\n return {};\n }\n}\n\n/**\n * Merge the generic cross-app builtin tools into the config's action\n * registry. **Template actions take precedence**: if a template defines an\n * action with the same name as a builtin (e.g. its own `list_apps`), the\n * template entry wins and the builtin is dropped. This mirrors the\n * template-over-workspace-core precedence in `autoDiscoverActions`.\n *\n * The builtins are pure-ish navigators / scaffolders; they call back into the\n * same `config.actions` / `config.askAgent` so there is no second agent loop.\n */\nfunction mergeBuiltinTools(\n config: MCPConfig,\n baseActions: Record<string, ActionEntry>,\n requestMeta?: MCPRequestMeta,\n): Record<string, ActionEntry> {\n if (config.builtinCrossAppTools === false) return baseActions;\n const builtins = getBuiltinCrossAppTools(config, requestMeta);\n const merged: Record<string, ActionEntry> = { ...builtins };\n // Template / app actions overwrite same-named builtins.\n for (const [name, entry] of Object.entries(baseActions)) {\n merged[name] = entry;\n }\n return merged;\n}\n\n// ---------------------------------------------------------------------------\n// MCP Server creation — converts ActionEntry registry to MCP tools\n// ---------------------------------------------------------------------------\n\n/**\n * Build a fully-wired MCP `Server` for a single request / session.\n *\n * Shared by the stateless Streamable-HTTP mount (`mountMCP`) and the stdio\n * standalone transport. The HTTP mount passes the per-request origin via\n * `requestMeta`; the stdio standalone path passes the resolved local app\n * origin so deep links still become absolute URLs.\n */\nexport async function createMCPServerForRequest(\n config: MCPConfig,\n identity: MCPCallerIdentity | undefined,\n requestMeta?: MCPRequestMeta,\n) {\n const { Server } = await import(\"@modelcontextprotocol/sdk/server/index.js\");\n const { ListToolsRequestSchema, CallToolRequestSchema } =\n await import(\"@modelcontextprotocol/sdk/types.js\");\n\n const server = new Server(\n { name: config.name, version: config.version ?? \"1.0.0\" },\n { capabilities: { tools: {} } },\n );\n\n // Resolve the effective caller identity. JWT / header-derived identity\n // (passed by `mountMCP` via `verifyAuth`) wins. When the caller passed no\n // identity — the stdio **standalone** path — fall back to the\n // `AGENT_NATIVE_OWNER_EMAIL` env the `agent-native mcp install` flow writes\n // into the `agent-native mcp serve` process env, so standalone tool runs are\n // tenant-scoped to the configured owner instead of running unscoped. Stays\n // undefined for true dev-open (no token, no secret, no owner) — behavior\n // there is unchanged.\n const ownerFromEnv = process.env.AGENT_NATIVE_OWNER_EMAIL?.trim();\n const effectiveIdentity: MCPCallerIdentity | undefined =\n identity ??\n (ownerFromEnv\n ? { userEmail: ownerFromEnv, orgDomain: undefined }\n : undefined);\n\n // The action set the request handlers operate on = base actions + generic\n // cross-app builtins (template wins on name collision). An authenticated\n // real caller (connect-minted token / `mcp install` owner / production —\n // `requestMeta.fullSurface`, or the stdio standalone path identified by\n // `AGENT_NATIVE_OWNER_EMAIL`) gets the full `productionActions` surface\n // even in local dev; the unauthenticated dev-open path keeps the sparse\n // `config.actions`. See `external-agents` skill, \"Dev vs production tool\n // surface\".\n const useFullSurface = requestMeta?.fullSurface === true || !!ownerFromEnv;\n const baseActions =\n useFullSurface && config.productionActions\n ? config.productionActions\n : config.actions;\n const actions = mergeBuiltinTools(config, baseActions, requestMeta);\n\n // Resolve orgId once per request (DB lookup) so subsequent wraps are\n // synchronous. The caller identity may be undefined for true dev-open —\n // in that case we run with no userEmail/orgId, which makes downstream\n // tools that require per-user scope return empty results rather than\n // cross-tenant data (the safe default).\n const orgIdPromise = resolveOrgIdFromDomain(effectiveIdentity?.orgDomain);\n\n /**\n * Wrap a callback in\n * `runWithRequestContext({ userEmail, orgId, requestOrigin }, fn)`.\n * Both the tools/list and tools/call handlers go through this so\n * downstream `accessFilter`, `resolveCredential`, and per-user MCP\n * visibility checks see the verified caller's identity. `requestOrigin`\n * is the live server origin derived from the inbound request (same value\n * used to absolutize deep links) so actions that build fetchable URLs\n * (e.g. design `export-coding-handoff`'s signed raw-code URL) resolve the\n * correct local-workspace origin instead of a prod/localhost fallback.\n */\n async function withCallerContext<T>(fn: () => Promise<T>): Promise<T> {\n const orgId = await orgIdPromise;\n return runWithRequestContext(\n {\n userEmail: effectiveIdentity?.userEmail,\n orgId,\n ...(requestMeta?.origin ? { requestOrigin: requestMeta.origin } : {}),\n },\n fn,\n ) as Promise<T>;\n }\n\n // tools/list — return all actions + ask-agent meta-tool. Wrapped in the\n // request context so per-user MCP visibility (mcp-client/visibility.ts)\n // applies to the listing too.\n server.setRequestHandler(ListToolsRequestSchema, async () => {\n return withCallerContext(async () => {\n const tools = Object.entries(actions).map(([name, entry]) => {\n const hasLink = typeof entry.link === \"function\";\n const baseDescription = entry.tool.description ?? name;\n return {\n name,\n description: hasLink\n ? `${baseDescription} After calling, surface the returned \"Open in … →\" link to the user.`\n : baseDescription,\n inputSchema: entry.tool.parameters ?? {\n type: \"object\" as const,\n properties: {},\n },\n ...(hasLink\n ? { annotations: { \"agent-native/producesOpenLink\": true } }\n : {}),\n };\n });\n\n if (config.askAgent) {\n tools.push({\n name: \"ask-agent\",\n description:\n \"Send a natural-language message to the app's AI agent and get a response. \" +\n \"Use this for complex, multi-step tasks that require the agent's reasoning \" +\n \"and full context about the app.\",\n inputSchema: {\n type: \"object\" as const,\n properties: {\n message: {\n type: \"string\",\n description: \"The message to send to the agent\",\n },\n },\n required: [\"message\"],\n },\n });\n }\n\n return { tools };\n });\n });\n\n // tools/call — dispatch to action registry or ask-agent. Wrapped in the\n // request context so the action's `run(args)` and `askAgent()` execute\n // with the verified caller's identity, not the platform default.\n server.setRequestHandler(CallToolRequestSchema, async (request: any) => {\n return withCallerContext(async () => {\n const { name, arguments: args } = request.params;\n\n if (name === \"ask-agent\" && config.askAgent) {\n const message = args?.message ?? \"\";\n try {\n const result = await config.askAgent(message);\n return { content: [{ type: \"text\", text: result }] };\n } catch (err: any) {\n return {\n content: [{ type: \"text\", text: `Error: ${err.message}` }],\n isError: true,\n };\n }\n }\n\n const entry = actions[name];\n if (!entry) {\n return {\n content: [{ type: \"text\", text: `Unknown tool: ${name}` }],\n isError: true,\n };\n }\n\n try {\n const result = await entry.run((args as Record<string, string>) ?? {});\n const text =\n typeof result === \"string\" ? result : JSON.stringify(result);\n const content: any[] = [{ type: \"text\", text }];\n const { block, _meta } = buildLinkArtifacts(\n entry,\n (args as Record<string, any>) ?? {},\n result,\n requestMeta,\n );\n if (block) content.push(block);\n return { content, ...(_meta ? { _meta } : {}) };\n } catch (err: any) {\n return {\n content: [{ type: \"text\", text: `Error: ${err.message}` }],\n isError: true,\n };\n }\n });\n });\n\n return server;\n}\n\n// ---------------------------------------------------------------------------\n// Auth — reuses the same pattern as A2A (Bearer token or JWT). Shared so the\n// HTTP mount and any stdio-side auth-aware helper resolve identity identically.\n// ---------------------------------------------------------------------------\n\nexport function getAccessTokens(): string[] {\n const single = process.env.ACCESS_TOKEN;\n const multi = process.env.ACCESS_TOKENS;\n const tokens: string[] = [];\n if (single) tokens.push(single);\n if (multi) {\n tokens.push(\n ...multi\n .split(\",\")\n .map((t) => t.trim())\n .filter(Boolean),\n );\n }\n return tokens;\n}\n\n/**\n * Resolve the caller identity for a static-token (or dev-open) auth path.\n *\n * Static `ACCESS_TOKEN` / `ACCESS_TOKENS` auth carries no per-caller claims,\n * so without this the MCP endpoint would run every tool with\n * `userEmail === undefined` and per-user / per-org scoped actions\n * (`accessFilter`, `resolveAccess`, `resolveCredential`) would return\n * empty / wrong data. The `agent-native mcp install` flow writes\n * `AGENT_NATIVE_OWNER_EMAIL` into the client config env and the stdio proxy\n * forwards it as the `X-Agent-Native-Owner-Email` request header (see\n * `mcp/stdio.ts#authHeaders`). We trust that owner hint *only* on the\n * static-token path — JWT auth already carries a cryptographically verified\n * `sub`, so the header is ignored there and never widens JWT scope.\n *\n * Precedence is server-trusted-first: the server process's\n * `AGENT_NATIVE_OWNER_EMAIL` env (set out-of-band by the operator / deploy)\n * ALWAYS wins, and a client-supplied `X-Agent-Native-Owner-Email` header is\n * honored *only as a fallback when that env is unset*. A static `ACCESS_TOKEN`\n * is a shared bearer secret; letting a request header override a\n * server-configured owner would let anyone holding a leaked token act as any\n * user. The header path remains for the single-tenant local-dev install flow\n * where the app server process has no owner env and the token *is* the\n * workspace secret; multi-tenant deployments must use A2A JWT (verified `sub`),\n * not a static token, for per-user scope.\n *\n * Returns `undefined` when no owner email is available (true dev-open: no\n * token, no secret, no owner) so behavior there stays unchanged.\n */\nfunction deriveStaticTokenIdentity(\n ownerEmailHeader: string | undefined,\n): MCPCallerIdentity | undefined {\n const owner =\n process.env.AGENT_NATIVE_OWNER_EMAIL?.trim() ||\n (typeof ownerEmailHeader === \"string\" && ownerEmailHeader.trim()) ||\n \"\";\n if (!owner) return undefined;\n return { userEmail: owner, orgDomain: undefined };\n}\n\n/**\n * Verify the inbound auth header. Returns:\n * - { authed: true, identity } when verified — `identity` is derived from\n * the JWT (`sub` / `org_domain`) for JWT auth, or from the\n * `AGENT_NATIVE_OWNER_EMAIL` env / `X-Agent-Native-Owner-Email` header\n * for static-token auth (the `agent-native mcp install` flow). `identity`\n * is undefined only for true dev-open with no owner hint.\n * - { authed: false } on rejection.\n *\n * When A2A_SECRET is set we extract the JWT's `sub` (caller email) and\n * `org_domain` claims so the MCP endpoint can wrap tool runs in\n * `runWithRequestContext({ userEmail, orgId })`. Without that wrap, the\n * MCP endpoint loses tenant identity and downstream `accessFilter` /\n * `resolveCredential` calls fall back to platform-wide defaults.\n *\n * `ownerEmailHeader` is the forwarded `X-Agent-Native-Owner-Email` value; it\n * is consulted ONLY on the static-token / dev-open path (never to influence\n * verified JWT identity), so the install flow runs tools as the configured\n * owner instead of an unscoped anonymous caller.\n */\nexport async function verifyAuth(\n authHeader: string | undefined,\n ownerEmailHeader?: string | undefined,\n options: { allowDevOpen?: boolean } = {},\n): Promise<{\n authed: boolean;\n identity?: MCPCallerIdentity;\n /**\n * The caller presented a real credential — a verified A2A/connect JWT, a\n * matching ACCESS_TOKEN, or (on the no-auth-configured path) a forwarded\n * owner-email header from `agent-native mcp install`. Drives the full vs\n * sparse MCP tool surface in local dev. The pure unauthenticated dev-open\n * path (no secret, no token, no owner header) is `false`.\n */\n fullSurface?: boolean;\n}> {\n // No auth configured → allow only when the route caller has already\n // established that this is a loopback/local dev request. Still honour an\n // owner hint there so the local install/connect flow stays tenant-scoped.\n const accessTokens = getAccessTokens();\n const hasA2ASecret = !!process.env.A2A_SECRET;\n if (accessTokens.length === 0 && !hasA2ASecret) {\n if (options.allowDevOpen === false) {\n return { authed: false };\n }\n return {\n authed: true,\n identity: deriveStaticTokenIdentity(ownerEmailHeader),\n // `mcp install`'s stdio proxy forwards an owner-email header even when\n // the local app has no secret configured — that is a real, identified\n // caller and gets the full surface. A bare browser/curl dev probe with\n // no owner hint stays on the sparse dev surface.\n fullSurface: !!(ownerEmailHeader && ownerEmailHeader.trim()),\n };\n }\n\n if (!authHeader?.startsWith(\"Bearer \")) return { authed: false };\n const token = authHeader.slice(7);\n\n // Try JWT via A2A_SECRET\n if (hasA2ASecret) {\n try {\n const jose = await import(\"jose\");\n const { payload } = await jose.jwtVerify(\n token,\n new TextEncoder().encode(process.env.A2A_SECRET!),\n );\n\n const tokenScope =\n typeof payload.scope === \"string\" ? payload.scope : undefined;\n if (tokenScope && tokenScope !== MCP_CONNECT_SCOPE) {\n return { authed: false };\n }\n\n // Connect-minted tokens (scope === \"mcp-connect\") carry a random `jti`\n // and are individually revocable. Only these tokens hit the revoke\n // store — ordinary A2A delegation JWTs skip the DB lookup entirely so\n // the hot path is unchanged. The revoke check FAILS OPEN on any\n // store/DB error: a transient Neon WS drop must never lock every\n // connected agent out. The signature was already cryptographically\n // verified above, so failing open here only widens the explicit-revoke\n // gate, never the trust boundary.\n if (tokenScope === MCP_CONNECT_SCOPE) {\n if (typeof payload.jti !== \"string\" || !payload.jti) {\n return { authed: false };\n }\n const jti = payload.jti;\n try {\n const { isJtiRevoked, touchTokenUsed } =\n await import(\"./connect-store.js\");\n if (await isJtiRevoked(jti)) {\n return { authed: false };\n }\n // Best-effort usage telemetry — never blocks / throws.\n void touchTokenUsed(jti);\n } catch {\n // Store import / lookup failed — fail open (see comment above).\n }\n }\n\n return {\n authed: true,\n identity: {\n userEmail: typeof payload.sub === \"string\" ? payload.sub : undefined,\n orgDomain:\n typeof payload.org_domain === \"string\"\n ? (payload.org_domain as string)\n : undefined,\n },\n // Verified JWT (connect-minted or A2A delegation) — a real caller.\n fullSurface: true,\n };\n } catch {\n // Not a valid JWT — fall through to token check\n }\n }\n\n // Try ACCESS_TOKEN / ACCESS_TOKENS exact match. Static tokens carry no\n // per-caller claims, so derive identity from the forwarded owner-email\n // hint (install flow) — otherwise tools would run unscoped.\n if (accessTokens.length > 0 && accessTokens.includes(token)) {\n return {\n authed: true,\n identity: deriveStaticTokenIdentity(ownerEmailHeader),\n // Matched a configured ACCESS_TOKEN — a real caller.\n fullSurface: true,\n };\n }\n\n return { authed: false };\n}\n\nexport async function resolveOrgIdFromDomain(\n orgDomain: string | undefined,\n): Promise<string | undefined> {\n if (!orgDomain) return undefined;\n try {\n const { resolveOrgByDomain } = await import(\"../org/context.js\");\n const org = await resolveOrgByDomain(orgDomain);\n return org?.orgId ?? undefined;\n } catch {\n return undefined;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"build-server.js","sourceRoot":"","sources":["../../src/mcp/build-server.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAGH,OAAO,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAC;AAChE,OAAO,EACL,oBAAoB,EACpB,iBAAiB,EACjB,6BAA6B,GAE9B,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,qBAAqB,EAAE,MAAM,8BAA8B,CAAC;AACrE,OAAO,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC7E,OAAO,EACL,yBAAyB,EACzB,8BAA8B,GAC/B,MAAM,gCAAgC,CAAC;AACxC,OA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AC,IAAI,YAAY,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;QAC5D,OAAO;YACL,MAAM,EAAE,IAAI;YACZ,QAAQ,EAAE,yBAAyB,CAAC,gBAAgB,CAAC;YACrD,qDAAqD;YACrD,WAAW,EAAE,IAAI;SAClB,CAAC;IACJ,CAAC;IAED,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC;AAC3B,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,sBAAsB,CAC1C,SAA6B;IAE7B,IAAI,CAAC,SAAS;QAAE,OAAO,SAAS,CAAC;IACjC,IAAI,CAAC;QACH,MAAM,EAAE,kBAAkB,EAAE,GAAG,MAAM,MAAM,CAAC,mBAAmB,CAAC,CAAC;QACjE,MAAM,GAAG,GAAG,MAAM,kBAAkB,CAAC,SAAS,CAAC,CAAC;QAChD,OAAO,GAAG,EAAE,KAAK,IAAI,SAAS,CAAC;IACjC,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,SAAS,CAAC;IACnB,CAAC;AACH,CAAC","sourcesContent":["/**\n * Shared MCP server builder.\n *\n * Extracted from `server.ts` so the stateless Streamable-HTTP mount\n * (`mountMCP`) and the stdio transport (`runMCPStdio --standalone`) build the\n * *same* MCP server from the *same* `ActionEntry` registry. Both surfaces:\n *\n * - expose every action as an MCP tool (+ the `ask-agent` meta-tool),\n * - append the framework deep-link block / `_meta` to every tool result,\n * - wrap `run()` / `askAgent()` in `runWithRequestContext` so per-user /\n * per-org scoping (accessFilter, resolveCredential, MCP visibility) is\n * honoured.\n *\n * `server.ts` re-exports `createMCPServerForRequest` and the auth helpers so\n * any (future) external importer of `@agent-native/core/mcp` keeps resolving.\n *\n * Node-only at the SDK level, but this module itself has no Node-only imports\n * — it can be bundled into the serverless function alongside `mountMCP`.\n */\n\nimport type { ActionEntry } from \"../agent/production-agent.js\";\nimport { isMcpActionResult } from \"../mcp-client/app-result.js\";\nimport {\n MCP_APP_EXTENSION_ID,\n MCP_APP_MIME_TYPE,\n MCP_APP_RESOURCE_URI_META_KEY,\n type ActionMcpAppResourceConfig,\n} from \"../action.js\";\nimport { runWithRequestContext } from \"../server/request-context.js\";\nimport { toAbsoluteOpenUrl, toDesktopOpenUrl } from \"../server/deep-link.js\";\nimport {\n isAgentNativeOpenDeepLink,\n withCollapsedAgentSidebarParam,\n} from \"../shared/agent-sidebar-url.js\";\nimport { getBuiltinCrossAppTools } from \"./builtin-tools.js\";\nimport { MCP_CONNECT_SCOPE } from \"./connect-store.js\";\nimport {\n MCP_OAUTH_SCOPES,\n hasMcpOAuthScope,\n verifyMcpOAuthAccessToken,\n} from \"./oauth-token.js\";\n\nexport interface MCPConfig {\n /** App name shown in MCP server info */\n name: string;\n /**\n * Canonical app id (directory under `apps/`, e.g. `mail`) this MCP server\n * is mounted for. Optional & back-compat: when omitted the builtin\n * cross-app tools fall back to lowercasing `name`. Used by `open_app` /\n * `ask_app` / `create_workspace_app` to tell \"this app\" from a cross-app\n * target so they resolve the *target* app's origin rather than echoing the\n * current request origin.\n */\n appId?: string;\n /** App description */\n description: string;\n /** Version string (default \"1.0.0\") */\n version?: string;\n /** Action registry — same as agent chat and A2A */\n actions: Record<string, ActionEntry>;\n /**\n * Full (\"production\") action surface served to an **authenticated real\n * caller** — a connect-minted token, an `agent-native mcp install` stdio\n * proxy (owner-email header / `AGENT_NATIVE_OWNER_EMAIL`), or a deployed /\n * `AGENT_MODE=production` app. In local dev `actions` is intentionally the\n * sparse, dev-toggled surface (builtins + read-only public-agent actions)\n * so the local agent chat and unauthenticated dev probes don't see every\n * mutating tool; but per the external-agents contract a real caller that\n * connected with a token MUST get the full surface even in dev. When unset\n * (production, where `actions` already IS the full set) the swap is a\n * no-op. See `external-agents` skill, \"Dev vs production tool surface\".\n */\n productionActions?: Record<string, ActionEntry>;\n /** Handler for the ask-agent meta-tool — runs the full agent loop */\n askAgent?: (message: string) => Promise<string>;\n /**\n * Disable the generic cross-app builtin tools (`list_apps`, `open_app`,\n * `ask_app`, `create_workspace_app`, `list_templates`). They are merged in\n * by default so external agents get a stable verb set; a template action of\n * the same name always wins (template precedence). Set to `false` only for\n * a constrained / locked-down mount.\n */\n builtinCrossAppTools?: boolean;\n}\n\n/**\n * Identity extracted from a verified MCP bearer token / JWT. Used to wrap\n * `entry.run()` and `config.askAgent()` calls in `runWithRequestContext`\n * so downstream tools (db-query, accessFilter, resolveCredential) honour\n * per-user / per-org scoping. Without this wrap the MCP endpoint would\n * silently bypass tenant isolation. See finding #6 in\n * /tmp/security-audit/12-mcp-a2a-agent.md.\n */\nexport interface MCPCallerIdentity {\n userEmail: string | undefined;\n orgDomain: string | undefined;\n /** Present only for standard remote MCP OAuth access tokens. */\n oauthScopes?: string[];\n}\n\n/** Per-request context used to turn an action's relative deep link into the\n * absolute web URL (and desktop `agentnative://` URL) the external agent\n * surfaces. Derived from the inbound request headers in `mountMCP`, or from\n * the resolved local app origin in the stdio standalone path. */\nexport interface MCPRequestMeta {\n /** Origin of the running app, e.g. `http://localhost:8100`. */\n origin?: string;\n /** Optional client preference for which URL the *markdown* link uses. */\n target?: \"browser\" | \"desktop\" | \"terminal\";\n /**\n * The caller authenticated with a real credential (verified A2A/connect\n * JWT, matching ACCESS_TOKEN, or a forwarded owner-email header from\n * `agent-native mcp install`) — not the unauthenticated local dev-open\n * path. When true, `createMCPServerForRequest` serves\n * `config.productionActions` (the full surface) instead of the sparse dev\n * `config.actions`. Set by `mountMCP` from `verifyAuth`.\n */\n fullSurface?: boolean;\n}\n\ntype McpOAuthScope = (typeof MCP_OAUTH_SCOPES)[number];\n\nfunction isActionVisibleForOAuthScope(\n entry: ActionEntry,\n scopes: string[] | undefined,\n): boolean {\n if (!scopes) return true;\n const required: McpOAuthScope =\n entry.readOnly === true ? \"mcp:read\" : \"mcp:write\";\n return hasMcpOAuthScope(scopes, required);\n}\n\ninterface ResolvedMcpAppResource {\n uri: string;\n name: string;\n title?: string;\n description?: string;\n html: ActionMcpAppResourceConfig[\"html\"];\n mimeType: typeof MCP_APP_MIME_TYPE;\n _meta?: Record<string, unknown>;\n}\n\n/**\n * Build the deep-link content block + structured `_meta` for a tool result.\n * Best-effort: any throw / nullish link is swallowed so a bad `link` builder\n * never fails the tool call.\n */\nexport function buildLinkArtifacts(\n entry: ActionEntry,\n args: Record<string, any>,\n result: any,\n meta: MCPRequestMeta | undefined,\n): {\n block?: { type: \"text\"; text: string };\n _meta?: Record<string, unknown>;\n} {\n if (typeof entry.link !== \"function\") return {};\n try {\n const lk = entry.link({ args: args ?? {}, result });\n if (!lk?.url) return {};\n const linkUrl = isAgentNativeOpenDeepLink(lk.url)\n ? withCollapsedAgentSidebarParam(lk.url)\n : lk.url;\n const webUrl = toAbsoluteOpenUrl(linkUrl, meta?.origin);\n const desktopUrl = toDesktopOpenUrl(linkUrl);\n const markdownUrl = meta?.target === \"desktop\" ? desktopUrl : webUrl;\n return {\n block: { type: \"text\", text: `\\n\\n[${lk.label} →](${markdownUrl})` },\n _meta: {\n \"agent-native/openLink\": {\n label: lk.label,\n view: lk.view,\n webUrl,\n desktopUrl,\n },\n },\n };\n } catch {\n return {};\n }\n}\n\n/**\n * Merge the generic cross-app builtin tools into the config's action\n * registry. **Template actions take precedence**: if a template defines an\n * action with the same name as a builtin (e.g. its own `list_apps`), the\n * template entry wins and the builtin is dropped. This mirrors the\n * template-over-workspace-core precedence in `autoDiscoverActions`.\n *\n * The builtins are pure-ish navigators / scaffolders; they call back into the\n * same `config.actions` / `config.askAgent` so there is no second agent loop.\n */\nfunction mergeBuiltinTools(\n config: MCPConfig,\n baseActions: Record<string, ActionEntry>,\n requestMeta?: MCPRequestMeta,\n): Record<string, ActionEntry> {\n if (config.builtinCrossAppTools === false) return baseActions;\n const builtins = getBuiltinCrossAppTools(config, requestMeta);\n const merged: Record<string, ActionEntry> = { ...builtins };\n // Template / app actions overwrite same-named builtins.\n for (const [name, entry] of Object.entries(baseActions)) {\n merged[name] = entry;\n }\n return merged;\n}\n\nfunction safeUiSegment(value: string | undefined, fallback: string): string {\n const normalized = (value || fallback)\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9._-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n return normalized || fallback;\n}\n\nfunction defaultMcpAppUri(config: MCPConfig, actionName: string): string {\n const app = safeUiSegment(config.appId ?? config.name, \"agent-native\");\n const action = safeUiSegment(actionName, \"tool\");\n return `ui://${app}/${action}`;\n}\n\nfunction mcpAppUiMeta(\n resource: ActionMcpAppResourceConfig,\n): Record<string, unknown> | undefined {\n const base =\n resource._meta && typeof resource._meta === \"object\"\n ? { ...resource._meta }\n : {};\n const existingUi =\n base.ui && typeof base.ui === \"object\" && !Array.isArray(base.ui)\n ? (base.ui as Record<string, unknown>)\n : {};\n const ui: Record<string, unknown> = { ...existingUi };\n if (resource.csp) ui.csp = resource.csp;\n if (resource.permissions) ui.permissions = resource.permissions;\n if (resource.domain) ui.domain = resource.domain;\n if (typeof resource.prefersBorder === \"boolean\") {\n ui.prefersBorder = resource.prefersBorder;\n }\n if (Object.keys(ui).length > 0) base.ui = ui;\n return Object.keys(base).length > 0 ? base : undefined;\n}\n\nfunction resolveMcpAppResource(\n config: MCPConfig,\n actionName: string,\n entry: ActionEntry,\n): ResolvedMcpAppResource | null {\n const resource = entry.mcpApp?.resource;\n if (!resource) return null;\n const uri = resource.uri?.trim() || defaultMcpAppUri(config, actionName);\n if (!uri.startsWith(\"ui://\")) return null;\n const resourceMeta = mcpAppUiMeta(resource);\n return {\n uri,\n name: resource.name?.trim() || actionName,\n ...(resource.title ? { title: resource.title } : {}),\n ...((resource.description ?? entry.tool.description)\n ? { description: resource.description ?? entry.tool.description }\n : {}),\n html: resource.html,\n mimeType: resource.mimeType ?? MCP_APP_MIME_TYPE,\n ...(resourceMeta ? { _meta: resourceMeta } : {}),\n };\n}\n\nfunction getMcpAppResources(\n config: MCPConfig,\n actions: Record<string, ActionEntry>,\n): ResolvedMcpAppResource[] {\n return Object.entries(actions).flatMap(([name, entry]) => {\n const resource = resolveMcpAppResource(config, name, entry);\n return resource ? [resource] : [];\n });\n}\n\nfunction renderMcpAppHtml(\n resource: ResolvedMcpAppResource,\n actionName: string,\n config: MCPConfig,\n requestMeta?: MCPRequestMeta,\n): string {\n if (typeof resource.html === \"function\") {\n return resource.html({\n actionName,\n appId: config.appId,\n requestOrigin: requestMeta?.origin,\n });\n }\n return resource.html;\n}\n\n// ---------------------------------------------------------------------------\n// MCP Server creation — converts ActionEntry registry to MCP tools\n// ---------------------------------------------------------------------------\n\n/**\n * Build a fully-wired MCP `Server` for a single request / session.\n *\n * Shared by the stateless Streamable-HTTP mount (`mountMCP`) and the stdio\n * standalone transport. The HTTP mount passes the per-request origin via\n * `requestMeta`; the stdio standalone path passes the resolved local app\n * origin so deep links still become absolute URLs.\n */\nexport async function createMCPServerForRequest(\n config: MCPConfig,\n identity: MCPCallerIdentity | undefined,\n requestMeta?: MCPRequestMeta,\n) {\n const { Server } = await import(\"@modelcontextprotocol/sdk/server/index.js\");\n const {\n ListToolsRequestSchema,\n CallToolRequestSchema,\n ListResourcesRequestSchema,\n ReadResourceRequestSchema,\n ListResourceTemplatesRequestSchema,\n } = await import(\"@modelcontextprotocol/sdk/types.js\");\n\n // Resolve the effective caller identity. JWT / header-derived identity\n // (passed by `mountMCP` via `verifyAuth`) wins. When the caller passed no\n // identity — the stdio **standalone** path — fall back to the\n // `AGENT_NATIVE_OWNER_EMAIL` env the `agent-native mcp install` flow writes\n // into the `agent-native mcp serve` process env, so standalone tool runs are\n // tenant-scoped to the configured owner instead of running unscoped. Stays\n // undefined for true dev-open (no token, no secret, no owner) — behavior\n // there is unchanged.\n const ownerFromEnv = process.env.AGENT_NATIVE_OWNER_EMAIL?.trim();\n const effectiveIdentity: MCPCallerIdentity | undefined =\n identity ??\n (ownerFromEnv\n ? { userEmail: ownerFromEnv, orgDomain: undefined }\n : undefined);\n\n // The action set the request handlers operate on = base actions + generic\n // cross-app builtins (template wins on name collision). An authenticated\n // real caller (connect-minted token / `mcp install` owner / production —\n // `requestMeta.fullSurface`, or the stdio standalone path identified by\n // `AGENT_NATIVE_OWNER_EMAIL`) gets the full `productionActions` surface\n // even in local dev; the unauthenticated dev-open path keeps the sparse\n // `config.actions`. See `external-agents` skill, \"Dev vs production tool\n // surface\".\n const useFullSurface = requestMeta?.fullSurface === true || !!ownerFromEnv;\n const baseActions =\n useFullSurface && config.productionActions\n ? config.productionActions\n : config.actions;\n const actions = mergeBuiltinTools(config, baseActions, requestMeta);\n const visibleActions = Object.fromEntries(\n Object.entries(actions).filter(([, entry]) =>\n isActionVisibleForOAuthScope(entry, effectiveIdentity?.oauthScopes),\n ),\n );\n const mcpAppResources = hasMcpOAuthScope(\n effectiveIdentity?.oauthScopes,\n \"mcp:apps\",\n )\n ? getMcpAppResources(config, visibleActions)\n : [];\n const supportsMcpApps = mcpAppResources.length > 0;\n const server = new Server(\n { name: config.name, version: config.version ?? \"1.0.0\" },\n {\n capabilities: {\n tools: {},\n ...(supportsMcpApps\n ? {\n resources: {},\n extensions: {\n [MCP_APP_EXTENSION_ID]: {\n mimeTypes: [MCP_APP_MIME_TYPE],\n },\n },\n }\n : {}),\n },\n },\n );\n\n // Resolve orgId once per request (DB lookup) so subsequent wraps are\n // synchronous. The caller identity may be undefined for true dev-open —\n // in that case we run with no userEmail/orgId, which makes downstream\n // tools that require per-user scope return empty results rather than\n // cross-tenant data (the safe default).\n const orgIdPromise = resolveOrgIdFromDomain(effectiveIdentity?.orgDomain);\n\n /**\n * Wrap a callback in\n * `runWithRequestContext({ userEmail, orgId, requestOrigin }, fn)`.\n * Both the tools/list and tools/call handlers go through this so\n * downstream `accessFilter`, `resolveCredential`, and per-user MCP\n * visibility checks see the verified caller's identity. `requestOrigin`\n * is the live server origin derived from the inbound request (same value\n * used to absolutize deep links) so actions that build fetchable URLs\n * (e.g. design `export-coding-handoff`'s signed raw-code URL) resolve the\n * correct local-workspace origin instead of a prod/localhost fallback.\n */\n async function withCallerContext<T>(fn: () => Promise<T>): Promise<T> {\n const orgId = await orgIdPromise;\n return runWithRequestContext(\n {\n userEmail: effectiveIdentity?.userEmail,\n orgId,\n ...(requestMeta?.origin ? { requestOrigin: requestMeta.origin } : {}),\n },\n fn,\n ) as Promise<T>;\n }\n\n // tools/list — return all actions + ask-agent meta-tool. Wrapped in the\n // request context so per-user MCP visibility (mcp-client/visibility.ts)\n // applies to the listing too.\n server.setRequestHandler(ListToolsRequestSchema, async () => {\n return withCallerContext(async () => {\n const tools = Object.entries(visibleActions).map(([name, entry]) => {\n const hasLink = typeof entry.link === \"function\";\n const mcpAppResource = resolveMcpAppResource(config, name, entry);\n const baseDescription = entry.tool.description ?? name;\n return {\n name,\n description: hasLink\n ? `${baseDescription} After calling, surface the returned \"Open in … →\" link to the user.`\n : baseDescription,\n inputSchema: entry.tool.parameters ?? {\n type: \"object\" as const,\n properties: {},\n },\n ...(mcpAppResource\n ? {\n _meta: {\n [MCP_APP_RESOURCE_URI_META_KEY]: mcpAppResource.uri,\n ui: {\n resourceUri: mcpAppResource.uri,\n visibility: entry.mcpApp?.visibility ?? [\"model\", \"app\"],\n },\n },\n }\n : {}),\n ...(hasLink\n ? { annotations: { \"agent-native/producesOpenLink\": true } }\n : {}),\n };\n });\n\n if (\n config.askAgent &&\n hasMcpOAuthScope(effectiveIdentity?.oauthScopes, \"mcp:write\")\n ) {\n tools.push({\n name: \"ask-agent\",\n description:\n \"Send a natural-language message to the app's AI agent and get a response. \" +\n \"Use this for complex, multi-step tasks that require the agent's reasoning \" +\n \"and full context about the app.\",\n inputSchema: {\n type: \"object\" as const,\n properties: {\n message: {\n type: \"string\",\n description: \"The message to send to the agent\",\n },\n },\n required: [\"message\"],\n },\n });\n }\n\n return { tools };\n });\n });\n\n // tools/call — dispatch to action registry or ask-agent. Wrapped in the\n // request context so the action's `run(args)` and `askAgent()` execute\n // with the verified caller's identity, not the platform default.\n server.setRequestHandler(CallToolRequestSchema, async (request: any) => {\n return withCallerContext(async () => {\n const { name, arguments: args } = request.params;\n\n if (name === \"ask-agent\" && config.askAgent) {\n if (!hasMcpOAuthScope(effectiveIdentity?.oauthScopes, \"mcp:write\")) {\n return {\n content: [\n {\n type: \"text\",\n text: \"Forbidden: OAuth scope does not allow ask-agent\",\n },\n ],\n isError: true,\n };\n }\n const message = args?.message ?? \"\";\n try {\n const result = await config.askAgent(message);\n return { content: [{ type: \"text\", text: result }] };\n } catch (err: any) {\n return {\n content: [{ type: \"text\", text: `Error: ${err.message}` }],\n isError: true,\n };\n }\n }\n\n const entry = actions[name];\n if (!entry) {\n return {\n content: [{ type: \"text\", text: `Unknown tool: ${name}` }],\n isError: true,\n };\n }\n if (\n !isActionVisibleForOAuthScope(entry, effectiveIdentity?.oauthScopes)\n ) {\n return {\n content: [\n {\n type: \"text\",\n text: `Forbidden: OAuth scope does not allow tool ${name}`,\n },\n ],\n isError: true,\n };\n }\n\n try {\n const result = await entry.run((args as Record<string, string>) ?? {});\n const resultForClient = isMcpActionResult(result)\n ? result.text\n : result;\n const text =\n typeof resultForClient === \"string\"\n ? resultForClient\n : JSON.stringify(resultForClient);\n const content: any[] = [{ type: \"text\", text }];\n const { block, _meta } = buildLinkArtifacts(\n entry,\n (args as Record<string, any>) ?? {},\n isMcpActionResult(result) ? result.raw : result,\n requestMeta,\n );\n if (block) content.push(block);\n return { content, ...(_meta ? { _meta } : {}) };\n } catch (err: any) {\n return {\n content: [{ type: \"text\", text: `Error: ${err.message}` }],\n isError: true,\n };\n }\n });\n });\n\n if (supportsMcpApps) {\n server.setRequestHandler(ListResourcesRequestSchema, async () => {\n return withCallerContext(async () => ({\n resources: mcpAppResources.map((resource) => ({\n uri: resource.uri,\n name: resource.name,\n ...(resource.title ? { title: resource.title } : {}),\n ...(resource.description\n ? { description: resource.description }\n : {}),\n mimeType: resource.mimeType,\n ...(resource._meta ? { _meta: resource._meta } : {}),\n })),\n }));\n });\n\n server.setRequestHandler(ListResourceTemplatesRequestSchema, async () => {\n return { resourceTemplates: [] };\n });\n\n server.setRequestHandler(\n ReadResourceRequestSchema,\n async (request: any) => {\n return withCallerContext(async () => {\n const uri = request.params?.uri;\n const found = Object.entries(visibleActions)\n .map(([name, entry]) => ({\n actionName: name,\n resource: resolveMcpAppResource(config, name, entry),\n }))\n .find((candidate) => candidate.resource?.uri === uri);\n if (!found?.resource) {\n throw new Error(`MCP App resource not found: ${uri}`);\n }\n return {\n contents: [\n {\n uri: found.resource.uri,\n mimeType: found.resource.mimeType,\n text: renderMcpAppHtml(\n found.resource,\n found.actionName,\n config,\n requestMeta,\n ),\n ...(found.resource._meta\n ? { _meta: found.resource._meta }\n : {}),\n },\n ],\n };\n });\n },\n );\n }\n\n return server;\n}\n\n// ---------------------------------------------------------------------------\n// Auth — reuses the same pattern as A2A (Bearer token or JWT). Shared so the\n// HTTP mount and any stdio-side auth-aware helper resolve identity identically.\n// ---------------------------------------------------------------------------\n\nexport function getAccessTokens(): string[] {\n const single = process.env.ACCESS_TOKEN;\n const multi = process.env.ACCESS_TOKENS;\n const tokens: string[] = [];\n if (single) tokens.push(single);\n if (multi) {\n tokens.push(\n ...multi\n .split(\",\")\n .map((t) => t.trim())\n .filter(Boolean),\n );\n }\n return tokens;\n}\n\n/**\n * Resolve the caller identity for a static-token (or dev-open) auth path.\n *\n * Static `ACCESS_TOKEN` / `ACCESS_TOKENS` auth carries no per-caller claims,\n * so without this the MCP endpoint would run every tool with\n * `userEmail === undefined` and per-user / per-org scoped actions\n * (`accessFilter`, `resolveAccess`, `resolveCredential`) would return\n * empty / wrong data. The `agent-native mcp install` flow writes\n * `AGENT_NATIVE_OWNER_EMAIL` into the client config env and the stdio proxy\n * forwards it as the `X-Agent-Native-Owner-Email` request header (see\n * `mcp/stdio.ts#authHeaders`). We trust that owner hint *only* on the\n * static-token path — JWT auth already carries a cryptographically verified\n * `sub`, so the header is ignored there and never widens JWT scope.\n *\n * Precedence is server-trusted-first: the server process's\n * `AGENT_NATIVE_OWNER_EMAIL` env (set out-of-band by the operator / deploy)\n * ALWAYS wins, and a client-supplied `X-Agent-Native-Owner-Email` header is\n * honored *only as a fallback when that env is unset*. A static `ACCESS_TOKEN`\n * is a shared bearer secret; letting a request header override a\n * server-configured owner would let anyone holding a leaked token act as any\n * user. The header path remains for the single-tenant local-dev install flow\n * where the app server process has no owner env and the token *is* the\n * workspace secret; multi-tenant deployments must use A2A JWT (verified `sub`),\n * not a static token, for per-user scope.\n *\n * Returns `undefined` when no owner email is available (true dev-open: no\n * token, no secret, no owner) so behavior there stays unchanged.\n */\nfunction deriveStaticTokenIdentity(\n ownerEmailHeader: string | undefined,\n): MCPCallerIdentity | undefined {\n const owner =\n process.env.AGENT_NATIVE_OWNER_EMAIL?.trim() ||\n (typeof ownerEmailHeader === \"string\" && ownerEmailHeader.trim()) ||\n \"\";\n if (!owner) return undefined;\n return { userEmail: owner, orgDomain: undefined };\n}\n\n/**\n * Verify the inbound auth header. Returns:\n * - { authed: true, identity } when verified — `identity` is derived from\n * the JWT (`sub` / `org_domain`) for JWT auth, or from the\n * `AGENT_NATIVE_OWNER_EMAIL` env / `X-Agent-Native-Owner-Email` header\n * for static-token auth (the `agent-native mcp install` flow). `identity`\n * is undefined only for true dev-open with no owner hint.\n * - { authed: false } on rejection.\n *\n * When A2A_SECRET is set we extract the JWT's `sub` (caller email) and\n * `org_domain` claims so the MCP endpoint can wrap tool runs in\n * `runWithRequestContext({ userEmail, orgId })`. Without that wrap, the\n * MCP endpoint loses tenant identity and downstream `accessFilter` /\n * `resolveCredential` calls fall back to platform-wide defaults.\n *\n * `ownerEmailHeader` is the forwarded `X-Agent-Native-Owner-Email` value; it\n * is consulted ONLY on the static-token / dev-open path (never to influence\n * verified JWT identity), so the install flow runs tools as the configured\n * owner instead of an unscoped anonymous caller.\n */\nexport async function verifyAuth(\n authHeader: string | undefined,\n ownerEmailHeader?: string | undefined,\n options: { allowDevOpen?: boolean; resourceUrl?: string } = {},\n): Promise<{\n authed: boolean;\n identity?: MCPCallerIdentity;\n /**\n * The caller presented a real credential — a verified A2A/connect JWT, a\n * matching ACCESS_TOKEN, or (on the no-auth-configured path) a forwarded\n * owner-email header from `agent-native mcp install`. Drives the full vs\n * sparse MCP tool surface in local dev. The pure unauthenticated dev-open\n * path (no secret, no token, no owner header) is `false`.\n */\n fullSurface?: boolean;\n}> {\n // No auth configured → allow only when the route caller has already\n // established that this is a loopback/local dev request. Still honour an\n // owner hint there so the local install/connect flow stays tenant-scoped.\n const accessTokens = getAccessTokens();\n const hasA2ASecret = !!process.env.A2A_SECRET;\n const token = authHeader?.startsWith(\"Bearer \")\n ? authHeader.slice(7)\n : undefined;\n if (token) {\n const oauthIdentity = await verifyMcpOAuthAccessToken(\n token,\n options.resourceUrl,\n );\n if (oauthIdentity) {\n return {\n authed: true,\n identity: {\n userEmail: oauthIdentity.userEmail,\n orgDomain: oauthIdentity.orgDomain,\n oauthScopes: oauthIdentity.scopes,\n },\n fullSurface: true,\n };\n }\n }\n if (accessTokens.length === 0 && !hasA2ASecret) {\n if (options.allowDevOpen === false) {\n return { authed: false };\n }\n return {\n authed: true,\n identity: deriveStaticTokenIdentity(ownerEmailHeader),\n // `mcp install`'s stdio proxy forwards an owner-email header even when\n // the local app has no secret configured — that is a real, identified\n // caller and gets the full surface. A bare browser/curl dev probe with\n // no owner hint stays on the sparse dev surface.\n fullSurface: !!(ownerEmailHeader && ownerEmailHeader.trim()),\n };\n }\n\n if (!token) return { authed: false };\n\n // Try JWT via A2A_SECRET\n if (hasA2ASecret) {\n try {\n const jose = await import(\"jose\");\n const { payload } = await jose.jwtVerify(\n token,\n new TextEncoder().encode(process.env.A2A_SECRET!),\n );\n\n const tokenScope =\n typeof payload.scope === \"string\" ? payload.scope : undefined;\n if (tokenScope && tokenScope !== MCP_CONNECT_SCOPE) {\n return { authed: false };\n }\n\n // Connect-minted tokens (scope === \"mcp-connect\") carry a random `jti`\n // and are individually revocable. Only these tokens hit the revoke\n // store — ordinary A2A delegation JWTs skip the DB lookup entirely so\n // the hot path is unchanged. The revoke check FAILS OPEN on any\n // store/DB error: a transient Neon WS drop must never lock every\n // connected agent out. The signature was already cryptographically\n // verified above, so failing open here only widens the explicit-revoke\n // gate, never the trust boundary.\n if (tokenScope === MCP_CONNECT_SCOPE) {\n if (typeof payload.jti !== \"string\" || !payload.jti) {\n return { authed: false };\n }\n const jti = payload.jti;\n try {\n const { isJtiRevoked, touchTokenUsed } =\n await import(\"./connect-store.js\");\n if (await isJtiRevoked(jti)) {\n return { authed: false };\n }\n // Best-effort usage telemetry — never blocks / throws.\n void touchTokenUsed(jti);\n } catch {\n // Store import / lookup failed — fail open (see comment above).\n }\n }\n\n return {\n authed: true,\n identity: {\n userEmail: typeof payload.sub === \"string\" ? payload.sub : undefined,\n orgDomain:\n typeof payload.org_domain === \"string\"\n ? (payload.org_domain as string)\n : undefined,\n },\n // Verified JWT (connect-minted or A2A delegation) — a real caller.\n fullSurface: true,\n };\n } catch {\n // Not a valid JWT — fall through to token check\n }\n }\n\n // Try ACCESS_TOKEN / ACCESS_TOKENS exact match. Static tokens carry no\n // per-caller claims, so derive identity from the forwarded owner-email\n // hint (install flow) — otherwise tools would run unscoped.\n if (accessTokens.length > 0 && accessTokens.includes(token)) {\n return {\n authed: true,\n identity: deriveStaticTokenIdentity(ownerEmailHeader),\n // Matched a configured ACCESS_TOKEN — a real caller.\n fullSurface: true,\n };\n }\n\n return { authed: false };\n}\n\nexport async function resolveOrgIdFromDomain(\n orgDomain: string | undefined,\n): Promise<string | undefined> {\n if (!orgDomain) return undefined;\n try {\n const { resolveOrgByDomain } = await import(\"../org/context.js\");\n const org = await resolveOrgByDomain(orgDomain);\n return org?.orgId ?? undefined;\n } catch {\n return undefined;\n }\n}\n"]}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Standard remote MCP OAuth 2.1 endpoints.
|
|
3
|
+
*
|
|
4
|
+
* These routes let MCP hosts such as Claude Code and ChatGPT authenticate
|
|
5
|
+
* through their native remote-MCP OAuth flow instead of pasting bearer tokens.
|
|
6
|
+
* The issued access tokens are audience-bound to `/_agent-native/mcp`, carry
|
|
7
|
+
* the same user/org identity as the existing connect flow, and are mediated by
|
|
8
|
+
* `verifyAuth` before any MCP tool/resource request runs.
|
|
9
|
+
*/
|
|
10
|
+
import type { H3Event } from "h3";
|
|
11
|
+
export interface McpOAuthRouteOptions {
|
|
12
|
+
appId?: string;
|
|
13
|
+
appName?: string;
|
|
14
|
+
}
|
|
15
|
+
export declare function getMcpOAuthIssuer(event: H3Event): string | undefined;
|
|
16
|
+
export declare function getMcpOAuthResource(event: H3Event): string | undefined;
|
|
17
|
+
export declare function getMcpOAuthProtectedResourceMetadataUrl(event: H3Event): string | undefined;
|
|
18
|
+
export declare function buildMcpOAuthChallenge(event: H3Event): string;
|
|
19
|
+
export declare function handleMcpOAuthProtectedResourceMetadata(event: H3Event): Response;
|
|
20
|
+
export declare function handleMcpOAuthAuthorizationServerMetadata(event: H3Event): Response;
|
|
21
|
+
export declare function handleMcpOAuth(event: H3Event, subpath: string, options?: McpOAuthRouteOptions): Promise<Response>;
|
|
22
|
+
//# sourceMappingURL=oauth-route.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"oauth-route.d.ts","sourceRoot":"","sources":["../../src/mcp/oauth-route.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,IAAI,CAAC;AAyBlC,MAAM,WAAW,oBAAoB;IACnC,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAkFD,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,GAAG,SAAS,CAIpE;AAED,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,GAAG,SAAS,CAItE;AAED,wBAAgB,uCAAuC,CACrD,KAAK,EAAE,OAAO,GACb,MAAM,GAAG,SAAS,CAIpB;AAED,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAM7D;AAiBD,wBAAgB,uCAAuC,CACrD,KAAK,EAAE,OAAO,GACb,QAAQ,CAeV;AAED,wBAAgB,yCAAyC,CACvD,KAAK,EAAE,OAAO,GACb,QAAQ,CAsBV;AA2jBD,wBAAsB,cAAc,CAClC,KAAK,EAAE,OAAO,EACd,OAAO,EAAE,MAAM,EACf,OAAO,GAAE,oBAAyB,GACjC,OAAO,CAAC,QAAQ,CAAC,CAenB"}
|