@agent-native/core 0.18.1 → 0.19.1
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/README.md +1 -11
- package/dist/a2a/caller-auth.d.ts +1 -0
- package/dist/a2a/caller-auth.d.ts.map +1 -1
- package/dist/a2a/caller-auth.js +1 -1
- package/dist/a2a/caller-auth.js.map +1 -1
- package/dist/a2a/client.d.ts +7 -0
- package/dist/a2a/client.d.ts.map +1 -1
- package/dist/a2a/client.js +3 -0
- package/dist/a2a/client.js.map +1 -1
- package/dist/agent/production-agent.d.ts +1 -1
- package/dist/agent/production-agent.d.ts.map +1 -1
- package/dist/agent/production-agent.js +34 -2
- package/dist/agent/production-agent.js.map +1 -1
- package/dist/cli/code-agent-executor.d.ts.map +1 -1
- package/dist/cli/code-agent-executor.js +47 -256
- package/dist/cli/code-agent-executor.js.map +1 -1
- package/dist/cli/connect.d.ts +94 -0
- package/dist/cli/connect.d.ts.map +1 -0
- package/dist/cli/connect.js +443 -0
- package/dist/cli/connect.js.map +1 -0
- package/dist/cli/index.js +16 -0
- package/dist/cli/index.js.map +1 -1
- package/dist/cli/mcp-config-writers.d.ts +71 -0
- package/dist/cli/mcp-config-writers.d.ts.map +1 -0
- package/dist/cli/mcp-config-writers.js +210 -0
- package/dist/cli/mcp-config-writers.js.map +1 -0
- package/dist/client/AgentPanel.d.ts +3 -1
- package/dist/client/AgentPanel.d.ts.map +1 -1
- package/dist/client/AgentPanel.js +4 -4
- package/dist/client/AgentPanel.js.map +1 -1
- package/dist/client/AssistantChat.d.ts +3 -0
- package/dist/client/AssistantChat.d.ts.map +1 -1
- package/dist/client/AssistantChat.js +22 -66
- package/dist/client/AssistantChat.js.map +1 -1
- package/dist/client/MultiTabAssistantChat.d.ts.map +1 -1
- package/dist/client/MultiTabAssistantChat.js +4 -1
- package/dist/client/MultiTabAssistantChat.js.map +1 -1
- package/dist/client/composer/PromptComposer.d.ts +6 -1
- package/dist/client/composer/PromptComposer.d.ts.map +1 -1
- package/dist/client/composer/PromptComposer.js +5 -4
- package/dist/client/composer/PromptComposer.js.map +1 -1
- package/dist/client/composer/TiptapComposer.d.ts +6 -1
- package/dist/client/composer/TiptapComposer.d.ts.map +1 -1
- package/dist/client/composer/TiptapComposer.js +20 -10
- package/dist/client/composer/TiptapComposer.js.map +1 -1
- package/dist/client/conversation/AgentConversation.d.ts +18 -0
- package/dist/client/conversation/AgentConversation.d.ts.map +1 -0
- package/dist/client/conversation/AgentConversation.js +94 -0
- package/dist/client/conversation/AgentConversation.js.map +1 -0
- package/dist/client/conversation/AgentConversation.spec.d.ts +2 -0
- package/dist/client/conversation/AgentConversation.spec.d.ts.map +1 -0
- package/dist/client/conversation/AgentConversation.spec.js +69 -0
- package/dist/client/conversation/AgentConversation.spec.js.map +1 -0
- package/dist/client/conversation/index.d.ts +4 -0
- package/dist/client/conversation/index.d.ts.map +1 -0
- package/dist/client/conversation/index.js +3 -0
- package/dist/client/conversation/index.js.map +1 -0
- package/dist/client/conversation/types.d.ts +54 -0
- package/dist/client/conversation/types.d.ts.map +1 -0
- package/dist/client/conversation/types.js +2 -0
- package/dist/client/conversation/types.js.map +1 -0
- package/dist/client/conversation/use-near-bottom-autoscroll.d.ts +15 -0
- package/dist/client/conversation/use-near-bottom-autoscroll.d.ts.map +1 -0
- package/dist/client/conversation/use-near-bottom-autoscroll.js +66 -0
- package/dist/client/conversation/use-near-bottom-autoscroll.js.map +1 -0
- package/dist/client/dynamic-suggestions.d.ts +43 -0
- package/dist/client/dynamic-suggestions.d.ts.map +1 -0
- package/dist/client/dynamic-suggestions.js +344 -0
- package/dist/client/dynamic-suggestions.js.map +1 -0
- package/dist/client/index.d.ts +2 -0
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +2 -0
- package/dist/client/index.js.map +1 -1
- package/dist/client/resources/ResourceTree.d.ts.map +1 -1
- package/dist/client/resources/ResourceTree.js +2 -2
- package/dist/client/resources/ResourceTree.js.map +1 -1
- package/dist/client/resources/ResourcesPanel.d.ts.map +1 -1
- package/dist/client/resources/ResourcesPanel.js +4 -28
- package/dist/client/resources/ResourcesPanel.js.map +1 -1
- package/dist/client/settings/SettingsPanel.js +2 -2
- package/dist/client/settings/SettingsPanel.js.map +1 -1
- package/dist/code-agents/index.d.ts +1 -0
- package/dist/code-agents/index.d.ts.map +1 -1
- package/dist/code-agents/index.js +1 -0
- package/dist/code-agents/index.js.map +1 -1
- package/dist/code-agents/transcript-normalizer.d.ts +50 -0
- package/dist/code-agents/transcript-normalizer.d.ts.map +1 -0
- package/dist/code-agents/transcript-normalizer.js +356 -0
- package/dist/code-agents/transcript-normalizer.js.map +1 -0
- package/dist/coding-tools/index.d.ts +31 -0
- package/dist/coding-tools/index.d.ts.map +1 -0
- package/dist/coding-tools/index.js +411 -0
- package/dist/coding-tools/index.js.map +1 -0
- package/dist/extensions/schema.d.ts +1 -1
- package/dist/mcp/build-server.d.ts.map +1 -1
- package/dist/mcp/build-server.js +30 -0
- package/dist/mcp/build-server.js.map +1 -1
- package/dist/mcp/builtin-tools.d.ts.map +1 -1
- package/dist/mcp/builtin-tools.js +85 -26
- package/dist/mcp/builtin-tools.js.map +1 -1
- package/dist/mcp/connect-route.d.ts +43 -0
- package/dist/mcp/connect-route.d.ts.map +1 -0
- package/dist/mcp/connect-route.js +744 -0
- package/dist/mcp/connect-route.js.map +1 -0
- package/dist/mcp/connect-store.d.ts +132 -0
- package/dist/mcp/connect-store.d.ts.map +1 -0
- package/dist/mcp/connect-store.js +434 -0
- package/dist/mcp/connect-store.js.map +1 -0
- package/dist/mcp/org-directory.d.ts +83 -0
- package/dist/mcp/org-directory.d.ts.map +1 -0
- package/dist/mcp/org-directory.js +201 -0
- package/dist/mcp/org-directory.js.map +1 -0
- package/dist/mcp/server.d.ts +38 -1
- package/dist/mcp/server.d.ts.map +1 -1
- package/dist/mcp/server.js +208 -77
- package/dist/mcp/server.js.map +1 -1
- package/dist/scripts/dev/index.d.ts +6 -4
- package/dist/scripts/dev/index.d.ts.map +1 -1
- package/dist/scripts/dev/index.js +28 -13
- package/dist/scripts/dev/index.js.map +1 -1
- package/dist/server/agent-chat-plugin.d.ts +6 -6
- package/dist/server/agent-chat-plugin.d.ts.map +1 -1
- package/dist/server/agent-chat-plugin.js +32 -32
- package/dist/server/agent-chat-plugin.js.map +1 -1
- package/dist/server/agent-teams.js +2 -2
- package/dist/server/agent-teams.js.map +1 -1
- package/dist/server/agents-bundle.d.ts +3 -3
- package/dist/server/agents-bundle.js +5 -5
- package/dist/server/agents-bundle.js.map +1 -1
- package/dist/server/auth.d.ts +17 -0
- package/dist/server/auth.d.ts.map +1 -1
- package/dist/server/auth.js +149 -33
- package/dist/server/auth.js.map +1 -1
- package/dist/server/better-auth-instance.d.ts +43 -0
- package/dist/server/better-auth-instance.d.ts.map +1 -1
- package/dist/server/better-auth-instance.js +25 -0
- package/dist/server/better-auth-instance.js.map +1 -1
- package/dist/server/core-routes-plugin.d.ts +12 -0
- package/dist/server/core-routes-plugin.d.ts.map +1 -1
- package/dist/server/core-routes-plugin.js +42 -0
- package/dist/server/core-routes-plugin.js.map +1 -1
- package/dist/server/identity-sso-store.d.ts +86 -0
- package/dist/server/identity-sso-store.d.ts.map +1 -0
- package/dist/server/identity-sso-store.js +243 -0
- package/dist/server/identity-sso-store.js.map +1 -0
- package/dist/server/identity-sso.d.ts +78 -0
- package/dist/server/identity-sso.d.ts.map +1 -0
- package/dist/server/identity-sso.js +425 -0
- package/dist/server/identity-sso.js.map +1 -0
- package/dist/server/index.d.ts +1 -0
- package/dist/server/index.d.ts.map +1 -1
- package/dist/server/index.js +1 -0
- package/dist/server/index.js.map +1 -1
- package/dist/server/onboarding-html.d.ts.map +1 -1
- package/dist/server/onboarding-html.js +2 -1
- package/dist/server/onboarding-html.js.map +1 -1
- package/dist/server/sentry.d.ts.map +1 -1
- package/dist/server/sentry.js +17 -2
- package/dist/server/sentry.js.map +1 -1
- package/dist/sharing/schema.d.ts +1 -1
- package/docs/content/client.md +15 -0
- package/docs/content/code-agents-ui.md +25 -4
- package/docs/content/cross-app-sso.md +118 -0
- package/docs/content/drop-in-agent.md +3 -1
- package/docs/content/external-agents.md +130 -51
- package/docs/content/frames.md +1 -1
- package/docs/content/migration-workbench.md +6 -1
- package/package.json +2 -1
|
@@ -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,EAAE,uBAAuB,EAAE,MAAM,oBAAoB,CAAC;AAwD7D;;;;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,KAAK,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,IAAI,IAAI,EAAE,EAAE,MAAM,EAAE,CAAC,CAAC;QACpD,IAAI,CAAC,EAAE,EAAE,GAAG;YAAE,OAAO,EAAE,CAAC;QACxB,MAAM,MAAM,GAAG,iBAAiB,CAAC,EAAE,CAAC,GAAG,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;QACvD,MAAM,UAAU,GAAG,gBAAgB,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC;QAC5C,MAAM,WAAW,GAAG,IAAI,EAAE,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,MAAM,CAAC;QACrE,OAAO;YACL,KAAK,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC,KAAK,OAAO,WAAW,GAAG,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Q,CAAC,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,SAAS;oBACpE,SAAS,EACP,OAAO,OAAO,CAAC,UAAU,KAAK,QAAQ;wBACpC,CAAC,CAAE,OAAO,CAAC,UAAqB;wBAChC,CAAC,CAAC,SAAS;iBAChB;aACF,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;SACtD,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 { getBuiltinCrossAppTools } from \"./builtin-tools.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 /** 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\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 webUrl = toAbsoluteOpenUrl(lk.url, meta?.origin);\n const desktopUrl = toDesktopOpenUrl(lk.url);\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(config: MCPConfig): Record<string, ActionEntry> {\n if (config.builtinCrossAppTools === false) return config.actions;\n const builtins = getBuiltinCrossAppTools(config);\n const merged: Record<string, ActionEntry> = { ...builtins };\n // Template / app actions overwrite same-named builtins.\n for (const [name, entry] of Object.entries(config.actions)) {\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 // The action set the request handlers operate on = template actions +\n // generic cross-app builtins (template wins on name collision).\n const actions = mergeBuiltinTools(config);\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 // 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): Promise<{ authed: boolean; identity?: MCPCallerIdentity }> {\n // No auth configured → allow (dev mode). Still honour an owner hint\n // (env or forwarded header) so the install flow stays tenant-scoped.\n const accessTokens = getAccessTokens();\n const hasA2ASecret = !!process.env.A2A_SECRET;\n if (accessTokens.length === 0 && !hasA2ASecret) {\n return {\n authed: true,\n identity: deriveStaticTokenIdentity(ownerEmailHeader),\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 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 };\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 };\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,qBAAqB,EAAE,MAAM,8BAA8B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AC;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 { 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 /** 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\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 webUrl = toAbsoluteOpenUrl(lk.url, meta?.origin);\n const desktopUrl = toDesktopOpenUrl(lk.url);\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(config: MCPConfig): Record<string, ActionEntry> {\n if (config.builtinCrossAppTools === false) return config.actions;\n const builtins = getBuiltinCrossAppTools(config);\n const merged: Record<string, ActionEntry> = { ...builtins };\n // Template / app actions overwrite same-named builtins.\n for (const [name, entry] of Object.entries(config.actions)) {\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 // The action set the request handlers operate on = template actions +\n // generic cross-app builtins (template wins on name collision).\n const actions = mergeBuiltinTools(config);\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 // 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): Promise<{ authed: boolean; identity?: MCPCallerIdentity }> {\n // No auth configured → allow (dev mode). Still honour an owner hint\n // (env or forwarded header) so the install flow stays tenant-scoped.\n const accessTokens = getAccessTokens();\n const hasA2ASecret = !!process.env.A2A_SECRET;\n if (accessTokens.length === 0 && !hasA2ASecret) {\n return {\n authed: true,\n identity: deriveStaticTokenIdentity(ownerEmailHeader),\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 };\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 };\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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"builtin-tools.d.ts","sourceRoot":"","sources":["../../src/mcp/builtin-tools.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAC;AAEhE,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;
|
|
1
|
+
{"version":3,"file":"builtin-tools.d.ts","sourceRoot":"","sources":["../../src/mcp/builtin-tools.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAC;AAEhE,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AA8enD;;;;GAIG;AACH,wBAAgB,uBAAuB,CACrC,MAAM,EAAE,SAAS,GAChB,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,CAQ7B"}
|
|
@@ -29,6 +29,7 @@
|
|
|
29
29
|
* `mountMCP` — the Node bits are dynamically imported inside `run()`.
|
|
30
30
|
*/
|
|
31
31
|
import { buildDeepLink } from "../server/deep-link.js";
|
|
32
|
+
import { fetchOrgApps } from "./org-directory.js";
|
|
32
33
|
/**
|
|
33
34
|
* Build an `ActionTool`. `parameters` is wrapped in the
|
|
34
35
|
* `{ type:"object", properties, required }` shape `createMCPServerForRequest`
|
|
@@ -87,25 +88,52 @@ async function resolveTargetAppOrigin(config, targetAppId) {
|
|
|
87
88
|
// ---------------------------------------------------------------------------
|
|
88
89
|
// list_apps
|
|
89
90
|
// ---------------------------------------------------------------------------
|
|
90
|
-
function listAppsTool() {
|
|
91
|
+
function listAppsTool(config) {
|
|
91
92
|
return {
|
|
92
|
-
tool: tool("List the workspace apps and their
|
|
93
|
-
"
|
|
94
|
-
"
|
|
93
|
+
tool: tool("List the workspace apps and their URLs. Use this to discover which " +
|
|
94
|
+
"apps exist before opening or asking one. In a single-app project " +
|
|
95
|
+
"this returns just that app. When an org directory is configured " +
|
|
96
|
+
"this also includes the org's deployed sibling apps."),
|
|
95
97
|
readOnly: true,
|
|
96
98
|
parallelSafe: true,
|
|
97
99
|
run: async () => {
|
|
98
100
|
const { resolveWorkspace } = await import("./workspace-resolve.js");
|
|
99
101
|
const ws = await resolveWorkspace();
|
|
102
|
+
const apps = ws.apps.map((a) => ({
|
|
103
|
+
id: a.id,
|
|
104
|
+
url: a.url,
|
|
105
|
+
port: a.port,
|
|
106
|
+
running: a.running,
|
|
107
|
+
source: "workspace",
|
|
108
|
+
}));
|
|
109
|
+
const seenIds = new Set(apps.map((a) => a.id.toLowerCase()));
|
|
110
|
+
const seenOrigins = new Set(apps.map((a) => a.url.replace(/\/+$/, "")));
|
|
111
|
+
// Merge the org directory's deployed sibling apps. Inactive (no env)
|
|
112
|
+
// or any failure ⇒ fetchOrgApps() returns [] and this is a no-op, so
|
|
113
|
+
// the existing local/workspace behavior is preserved exactly.
|
|
114
|
+
const orgApps = await fetchOrgApps({
|
|
115
|
+
selfId: currentAppId(config),
|
|
116
|
+
}).catch(() => []);
|
|
117
|
+
for (const oa of orgApps) {
|
|
118
|
+
const idKey = oa.id.toLowerCase();
|
|
119
|
+
const originKey = oa.url.replace(/\/+$/, "");
|
|
120
|
+
// Dedupe by id OR origin — a workspace app already listed wins.
|
|
121
|
+
if (seenIds.has(idKey) || seenOrigins.has(originKey))
|
|
122
|
+
continue;
|
|
123
|
+
seenIds.add(idKey);
|
|
124
|
+
seenOrigins.add(originKey);
|
|
125
|
+
apps.push({
|
|
126
|
+
id: oa.id,
|
|
127
|
+
url: oa.url,
|
|
128
|
+
port: undefined,
|
|
129
|
+
running: true,
|
|
130
|
+
source: "org-directory",
|
|
131
|
+
});
|
|
132
|
+
}
|
|
100
133
|
return {
|
|
101
134
|
workspace: ws.isWorkspace,
|
|
102
135
|
gatewayUrl: ws.gatewayUrl,
|
|
103
|
-
apps
|
|
104
|
-
id: a.id,
|
|
105
|
-
url: a.url,
|
|
106
|
-
port: a.port,
|
|
107
|
-
running: a.running,
|
|
108
|
-
})),
|
|
136
|
+
apps,
|
|
109
137
|
};
|
|
110
138
|
},
|
|
111
139
|
};
|
|
@@ -175,6 +203,33 @@ function openAppTool(config) {
|
|
|
175
203
|
},
|
|
176
204
|
};
|
|
177
205
|
}
|
|
206
|
+
/**
|
|
207
|
+
* Route an `ask_app` message to a *different* app's agent over A2A. Shared by
|
|
208
|
+
* the workspace-resolved path and the org-directory-resolved path so the A2A
|
|
209
|
+
* call logic is not duplicated. `origin` is the target app's A2A base
|
|
210
|
+
* (workspace dev origin or the directory's `a2aUrl`); `id` is reported back.
|
|
211
|
+
*
|
|
212
|
+
* Throws on failure so the caller can be honest — it never falls back to this
|
|
213
|
+
* app's agent and pretends it was the target.
|
|
214
|
+
*/
|
|
215
|
+
async function routeAskOverA2A(origin, id, message) {
|
|
216
|
+
const { callAgent } = await import("../a2a/client.js");
|
|
217
|
+
const { resolveA2ACallerAuth } = await import("../a2a/caller-auth.js");
|
|
218
|
+
// The MCP handler runs inside `runWithRequestContext`, so this is the
|
|
219
|
+
// verified caller identity and org scope. Reuse the same auth resolver as
|
|
220
|
+
// org-directory discovery so the directory lookup and actual A2A call are
|
|
221
|
+
// scoped the same way.
|
|
222
|
+
const auth = await resolveA2ACallerAuth();
|
|
223
|
+
const response = await callAgent(origin, message, {
|
|
224
|
+
apiKey: auth.apiKey,
|
|
225
|
+
userEmail: auth.userEmail,
|
|
226
|
+
orgDomain: auth.orgDomain,
|
|
227
|
+
orgSecret: auth.orgSecret,
|
|
228
|
+
// Bound the wait — cross-app A2A polls async by default.
|
|
229
|
+
timeoutMs: 5 * 60_000,
|
|
230
|
+
});
|
|
231
|
+
return { app: id, routedVia: "a2a", response };
|
|
232
|
+
}
|
|
178
233
|
// ---------------------------------------------------------------------------
|
|
179
234
|
// ask_app
|
|
180
235
|
// ---------------------------------------------------------------------------
|
|
@@ -208,21 +263,7 @@ function askAppTool(config) {
|
|
|
208
263
|
const targetApp = await resolveTargetAppOrigin(config, requestedApp);
|
|
209
264
|
if (targetApp) {
|
|
210
265
|
try {
|
|
211
|
-
|
|
212
|
-
const { getRequestUserEmail } = await import("../server/request-context.js");
|
|
213
|
-
// The MCP handler runs inside `runWithRequestContext`, so this is
|
|
214
|
-
// the verified caller's email — it lets `callAgent` mint a signed
|
|
215
|
-
// A2A JWT so the target app honours per-user scope.
|
|
216
|
-
const response = await callAgent(targetApp.origin, message, {
|
|
217
|
-
userEmail: getRequestUserEmail(),
|
|
218
|
-
// Bound the wait — cross-app A2A polls async by default.
|
|
219
|
-
timeoutMs: 5 * 60_000,
|
|
220
|
-
});
|
|
221
|
-
return {
|
|
222
|
-
app: targetApp.id,
|
|
223
|
-
routedVia: "a2a",
|
|
224
|
-
response,
|
|
225
|
-
};
|
|
266
|
+
return await routeAskOverA2A(targetApp.origin, targetApp.id, message);
|
|
226
267
|
}
|
|
227
268
|
catch (err) {
|
|
228
269
|
// Be honest: routing was attempted and failed — do NOT fall back to
|
|
@@ -231,6 +272,24 @@ function askAppTool(config) {
|
|
|
231
272
|
`${err?.message ?? err}`);
|
|
232
273
|
}
|
|
233
274
|
}
|
|
275
|
+
// Not a known local/workspace app — try the org directory. When a
|
|
276
|
+
// directory is configured and the requested app is one of the org's
|
|
277
|
+
// deployed sibling apps, route to it over A2A (same path as above,
|
|
278
|
+
// against its `a2aUrl`). Inactive directory / any failure ⇒ orgApps is
|
|
279
|
+
// [] and this is skipped, preserving the exact local-only behavior.
|
|
280
|
+
if (requestedApp && requestedApp.toLowerCase() !== selfId) {
|
|
281
|
+
const orgApps = await fetchOrgApps({ selfId }).catch(() => []);
|
|
282
|
+
const dirMatch = orgApps.find((a) => a.id === requestedApp.toLowerCase());
|
|
283
|
+
if (dirMatch) {
|
|
284
|
+
try {
|
|
285
|
+
return await routeAskOverA2A(dirMatch.a2aUrl, dirMatch.id, message);
|
|
286
|
+
}
|
|
287
|
+
catch (err) {
|
|
288
|
+
throw new Error(`Failed to route ask_app to "${dirMatch.id}" via A2A ` +
|
|
289
|
+
`(org directory): ${err?.message ?? err}`);
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
}
|
|
234
293
|
// Same app (or no workspace / unknown target): answer locally with this
|
|
235
294
|
// app's own ask-agent handler — the same entry point the HTTP MCP mount
|
|
236
295
|
// + A2A use, so there is no second agent runner.
|
|
@@ -391,7 +450,7 @@ function createWorkspaceAppTool() {
|
|
|
391
450
|
*/
|
|
392
451
|
export function getBuiltinCrossAppTools(config) {
|
|
393
452
|
return {
|
|
394
|
-
list_apps: listAppsTool(),
|
|
453
|
+
list_apps: listAppsTool(config),
|
|
395
454
|
open_app: openAppTool(config),
|
|
396
455
|
ask_app: askAppTool(config),
|
|
397
456
|
create_workspace_app: createWorkspaceAppTool(),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"builtin-tools.js","sourceRoot":"","sources":["../../src/mcp/builtin-tools.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAGH,OAAO,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AAWvD;;;;GAIG;AACH,SAAS,IAAI,CACX,WAAmB,EACnB,UAAmB,EACnB,QAAmB;IAEnB,IAAI,CAAC,UAAU;QAAE,OAAO,EAAE,WAAW,EAAE,CAAC;IACxC,OAAO;QACL,WAAW;QACX,UAAU,EAAE;YACV,IAAI,EAAE,QAAQ;YACd,UAAU,EAAE,UAAU;YACtB,GAAG,CAAC,QAAQ,IAAI,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SACrD;KACF,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,SAAS,YAAY,CAAC,MAAiB;IACrC,OAAO,CAAC,MAAM,CAAC,KAAK,IAAI,MAAM,CAAC,IAAI,IAAI,KAAK,CAAC,CAAC,WAAW,EAAE,CAAC;AAC9D,CAAC;AAED;;;;;;;;;;GAUG;AACH,KAAK,UAAU,sB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E,OAAO,IAAI,CAAC;YACvD,MAAM,CAAC,GAAG,MAA8C,CAAC;YACzD,IAAI,CAAC,CAAC,CAAC,QAAQ;gBAAE,OAAO,IAAI,CAAC;YAC7B,OAAO;gBACL,GAAG,EAAE,CAAC,CAAC,QAAQ;gBACf,KAAK,EAAE,QAAQ,CAAC,CAAC,IAAI,IAAI,KAAK,EAAE;gBAChC,IAAI,EAAE,MAAM;aACb,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC;AAED,8EAA8E;AAC9E,WAAW;AACX,8EAA8E;AAE9E;;;;GAIG;AACH,MAAM,UAAU,uBAAuB,CACrC,MAAiB;IAEjB,OAAO;QACL,SAAS,EAAE,YAAY,EAAE;QACzB,QAAQ,EAAE,WAAW,CAAC,MAAM,CAAC;QAC7B,OAAO,EAAE,UAAU,CAAC,MAAM,CAAC;QAC3B,oBAAoB,EAAE,sBAAsB,EAAE;QAC9C,cAAc,EAAE,iBAAiB,EAAE;KACpC,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Generic cross-app MCP tools — a stable verb set every external agent gets\n * regardless of which template it is talking to.\n *\n * These are merged into the MCP action registry by\n * `createMCPServerForRequest` (see `build-server.ts`). **Precedence: template\n * actions win.** If a template defines an action named `list_apps` /\n * `open_app` / `ask_app` / `create_workspace_app` / `list_templates`, the\n * template's `ActionEntry` overwrites the builtin of the same name. This is\n * the same template-over-framework precedence `autoDiscoverActions` uses.\n *\n * | Tool | Side effects | Returns |\n * | --------------------- | ------------ | ---------------------------------------- |\n * | `list_apps` | none | `{ apps: [{ id, url, running }] }` |\n * | `open_app` | none | `{ url }` (+ deep-link `link`) |\n * | `ask_app` | agent loop | `{ app, routedVia, response }` |\n * | `create_workspace_app`| scaffolds | `{ name, url, port, deepLink }` (+ link) |\n *\n * `open_app` / `create_workspace_app` return an **absolute** URL on the\n * *target* app's origin when it differs from this app (so a workspace link\n * lands in the right app), and a relative path for the same app / standalone.\n * `ask_app` routes to a *different* workspace app over A2A when possible and\n * reports `routedVia: \"a2a\"`; otherwise it answers locally\n * (`routedVia: \"local\"`) and never falsely claims cross-app delegation.\n * | `list_templates` | none | `{ templates: [...] }` (allow-list only) |\n *\n * Node-only at call time (workspace resolution + scaffolding use `fs`), but\n * the module has no top-level Node imports so it bundles fine alongside\n * `mountMCP` — the Node bits are dynamically imported inside `run()`.\n */\n\nimport type { ActionEntry } from \"../agent/production-agent.js\";\nimport { buildDeepLink } from \"../server/deep-link.js\";\nimport type { MCPConfig } from \"./build-server.js\";\n\nimport type { ActionTool } from \"../agent/types.js\";\n\n/** Flat map of param name → JSON-schema property. */\ntype Params = Record<\n string,\n { type: string; description?: string; enum?: string[] }\n>;\n\n/**\n * Build an `ActionTool`. `parameters` is wrapped in the\n * `{ type:\"object\", properties, required }` shape `createMCPServerForRequest`\n * forwards verbatim as the MCP tool `inputSchema`.\n */\nfunction tool(\n description: string,\n parameters?: Params,\n required?: string[],\n): ActionTool {\n if (!parameters) return { description };\n return {\n description,\n parameters: {\n type: \"object\",\n properties: parameters,\n ...(required && required.length ? { required } : {}),\n },\n };\n}\n\n/**\n * The canonical app id this MCP server is mounted for. `MCPConfig.appId` is\n * authoritative; fall back to lowercasing `name` (which is the capitalized\n * app id at every call site) for back-compat with configs that predate the\n * `appId` field.\n */\nfunction currentAppId(config: MCPConfig): string {\n return (config.appId || config.name || \"app\").toLowerCase();\n}\n\n/**\n * Resolve the absolute origin of a *target* workspace app (e.g.\n * `http://127.0.0.1:8101`) so cross-app deep links / A2A calls point at the\n * right app instead of the current request's origin. Reuses the same\n * workspace resolution `list_apps` / the stdio proxy use.\n *\n * Returns `null` when:\n * - the target is the current app (caller should keep relative behavior),\n * - there is no workspace info (standalone / single app), or\n * - the target app is unknown.\n */\nasync function resolveTargetAppOrigin(\n config: MCPConfig,\n targetAppId: string,\n): Promise<{ origin: string; id: string } | null> {\n const target = targetAppId.trim().toLowerCase();\n if (!target || target === currentAppId(config)) return null;\n try {\n const { resolveWorkspace } = await import(\"./workspace-resolve.js\");\n const ws = await resolveWorkspace();\n if (!ws.isWorkspace) return null;\n const match = ws.apps.find((a) => a.id.toLowerCase() === target);\n if (!match) return null;\n return { origin: match.url, id: match.id };\n } catch {\n return null;\n }\n}\n\n// ---------------------------------------------------------------------------\n// list_apps\n// ---------------------------------------------------------------------------\n\nfunction listAppsTool(): ActionEntry {\n return {\n tool: tool(\n \"List the workspace apps and their local dev URLs/ports. Use this to \" +\n \"discover which apps exist before opening or asking one. In a single-\" +\n \"app project this returns just that app.\",\n ),\n readOnly: true,\n parallelSafe: true,\n run: async () => {\n const { resolveWorkspace } = await import(\"./workspace-resolve.js\");\n const ws = await resolveWorkspace();\n return {\n workspace: ws.isWorkspace,\n gatewayUrl: ws.gatewayUrl,\n apps: ws.apps.map((a) => ({\n id: a.id,\n url: a.url,\n port: a.port,\n running: a.running,\n })),\n };\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// open_app\n// ---------------------------------------------------------------------------\n\nfunction openAppTool(config: MCPConfig): ActionEntry {\n return {\n tool: tool(\n \"Build a deep link that opens an app at a specific view/record. No side \" +\n \"effects — returns a URL the user can click to land in the running UI. \" +\n 'After calling, surface the returned \"Open in … →\" link to the user.',\n {\n app: { type: \"string\", description: \"App id, e.g. 'mail'\" },\n view: {\n type: \"string\",\n description: \"Target view, e.g. 'inbox' (maps to navigate command)\",\n },\n params: {\n type: \"object\",\n description:\n \"Optional record-focus / filter params, e.g. { threadId: 'abc' }\",\n },\n },\n [\"app\", \"view\"],\n ),\n readOnly: true,\n parallelSafe: true,\n run: async (args: Record<string, any>) => {\n const app = String(args.app ?? \"\").trim();\n const view = String(args.view ?? \"\").trim();\n if (!app || !view) {\n throw new Error(\"open_app requires both 'app' and 'view'.\");\n }\n let params: Record<string, string | number | boolean> | undefined;\n const raw = args.params;\n if (raw && typeof raw === \"object\") {\n params = raw as Record<string, string | number | boolean>;\n } else if (typeof raw === \"string\" && raw.trim()) {\n try {\n params = JSON.parse(raw);\n } catch {\n params = undefined;\n }\n }\n const relUrl = buildDeepLink({ app, view, params });\n\n // Cross-app target in a workspace: resolve the TARGET app's origin and\n // return an absolute URL. Otherwise the MCP layer would prefix the\n // relative path with the CURRENT request origin, landing the user in\n // the wrong app (e.g. open_app({app:\"calendar\"}) served from Mail).\n // Same-app / standalone keeps the relative path (current behavior).\n const targetApp = await resolveTargetAppOrigin(config, app);\n const url = targetApp\n ? `${targetApp.origin.replace(/\\/+$/, \"\")}${relUrl}`\n : relUrl;\n\n return { app, view, url };\n },\n link: ({ result }) => {\n if (!result || typeof result !== \"object\") return null;\n const r = result as { url?: string; app?: string; view?: string };\n if (!r.url) return null;\n return {\n url: r.url,\n label: `Open ${r.app ?? \"app\"}`,\n view: r.view,\n };\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// ask_app\n// ---------------------------------------------------------------------------\n\nfunction askAppTool(config: MCPConfig): ActionEntry {\n return {\n tool: tool(\n \"Send a natural-language message to an app's AI agent and get its \" +\n \"response. Use for complex, multi-step tasks needing the agent's \" +\n \"reasoning and full app context. In a single-app project the 'app' \" +\n \"param is optional (defaults to this app). When 'app' names a \" +\n \"different workspace app it is routed there over A2A; the result's \" +\n \"'routedVia' field reports whether it ran cross-app or locally.\",\n {\n app: {\n type: \"string\",\n description: \"App id to route to (optional in a single-app project)\",\n },\n message: {\n type: \"string\",\n description: \"The message to send to the app's agent\",\n },\n },\n [\"message\"],\n ),\n run: async (args: Record<string, any>) => {\n const message = String(args.message ?? \"\").trim();\n if (!message) throw new Error(\"ask_app requires a 'message'.\");\n const requestedApp = String(args.app ?? \"\").trim();\n const selfId = currentAppId(config);\n\n // Cross-app: the caller named a *different* workspace app. Route the\n // message to THAT app's agent over A2A (its `/_agent-native/a2a`\n // endpoint runs the real agent loop with JWT identity) rather than\n // silently answering from this app's agent and claiming delegation.\n const targetApp = await resolveTargetAppOrigin(config, requestedApp);\n if (targetApp) {\n try {\n const { callAgent } = await import(\"../a2a/client.js\");\n const { getRequestUserEmail } =\n await import(\"../server/request-context.js\");\n // The MCP handler runs inside `runWithRequestContext`, so this is\n // the verified caller's email — it lets `callAgent` mint a signed\n // A2A JWT so the target app honours per-user scope.\n const response = await callAgent(targetApp.origin, message, {\n userEmail: getRequestUserEmail(),\n // Bound the wait — cross-app A2A polls async by default.\n timeoutMs: 5 * 60_000,\n });\n return {\n app: targetApp.id,\n routedVia: \"a2a\",\n response,\n };\n } catch (err: any) {\n // Be honest: routing was attempted and failed — do NOT fall back to\n // this app's agent and pretend it was the target.\n throw new Error(\n `Failed to route ask_app to \"${targetApp.id}\" via A2A: ` +\n `${err?.message ?? err}`,\n );\n }\n }\n\n // Same app (or no workspace / unknown target): answer locally with this\n // app's own ask-agent handler — the same entry point the HTTP MCP mount\n // + A2A use, so there is no second agent runner.\n if (!config.askAgent) {\n throw new Error(\n \"This app does not expose an agent (no ask-agent handler).\",\n );\n }\n\n // If the caller named an app we couldn't route to (unknown id, or no\n // workspace), say so honestly instead of claiming we reached it.\n const unresolved =\n !!requestedApp && requestedApp.toLowerCase() !== selfId;\n const response = await config.askAgent(message);\n return {\n app: selfId,\n routedVia: \"local\",\n ...(unresolved\n ? {\n note:\n `Requested app \"${requestedApp}\" is not a reachable workspace ` +\n `app; answered with this app (\"${selfId}\") instead.`,\n }\n : {}),\n response,\n };\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// list_templates\n// ---------------------------------------------------------------------------\n\nfunction listTemplatesTool(): ActionEntry {\n return {\n tool: tool(\n \"List the first-party templates that can be scaffolded into a workspace \" +\n \"(allow-listed templates only).\",\n ),\n readOnly: true,\n parallelSafe: true,\n run: async () => {\n const { visibleTemplates } = await import(\"../cli/templates-meta.js\");\n return {\n templates: visibleTemplates().map((t) => ({\n name: t.name,\n label: t.label,\n hint: t.hint,\n })),\n };\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// create_workspace_app\n// ---------------------------------------------------------------------------\n\nfunction createWorkspaceAppTool(): ActionEntry {\n return {\n tool: tool(\n \"Scaffold a new app into the current workspace from an allow-listed \" +\n \"template, then return a deep link to open it. Idempotent: if an app \" +\n \"with that name already exists it is reused. After calling, surface \" +\n 'the returned \"Open … →\" link to the user.',\n {\n name: {\n type: \"string\",\n description: \"New app id (directory under apps/), e.g. 'mymail'\",\n },\n template: {\n type: \"string\",\n description:\n \"Template to scaffold from — must be allow-listed (see list_templates)\",\n },\n },\n [\"name\", \"template\"],\n ),\n run: async (args: Record<string, any>) => {\n const name = String(args.name ?? \"\").trim();\n const template = String(args.template ?? \"\").trim();\n if (!name || !template) {\n throw new Error(\n \"create_workspace_app requires both 'name' and 'template'.\",\n );\n }\n\n // Enforce the strict public template allow-list. The authoritative,\n // dependency-free source inside @agent-native/core is cli/templates-meta\n // (kept in sync with packages/shared-app-config/templates.ts; CI guard).\n const { visibleTemplates } = await import(\"../cli/templates-meta.js\");\n const allowed = new Set(visibleTemplates().map((t) => t.name));\n if (!allowed.has(template)) {\n throw new Error(\n `Template \"${template}\" is not allow-listed. Allowed: ${[...allowed]\n .sort()\n .join(\", \")}`,\n );\n }\n\n const { findWorkspaceRoot, resolveWorkspace } =\n await import(\"./workspace-resolve.js\");\n const fs = await import(\"node:fs\");\n const path = await import(\"node:path\");\n\n const root = findWorkspaceRoot(process.cwd());\n if (!root) {\n throw new Error(\n \"Not inside a workspace. create_workspace_app only works in a \" +\n \"multi-app workspace (run from the workspace root).\",\n );\n }\n\n const appDir = path.join(root, \"apps\", name);\n const alreadyExisted = fs.existsSync(appDir);\n\n if (!alreadyExisted) {\n // Reuse the CLI scaffolder directly (no second `agent-native`\n // subprocess). `addAppToWorkspace(name, { template })` takes the\n // non-interactive single-template path when name + one template are\n // given. Run it from the workspace root so detectWorkspace resolves.\n const prevCwd = process.cwd();\n try {\n process.chdir(root);\n const { addAppToWorkspace } = await import(\"../cli/create.js\");\n await addAppToWorkspace(name, { template, noInstall: true });\n } finally {\n try {\n process.chdir(prevCwd);\n } catch {\n // best-effort cwd restore\n }\n }\n }\n\n // The workspace gateway auto-detects new apps/* dirs (fs.watch +\n // 2s sync) and lazily boots the dev server on first request, so we\n // don't spawn vite ourselves — opening the deep link warms it. Resolve\n // the port the gateway will use so we can report it.\n const ws = await resolveWorkspace(root);\n const appInfo = ws.apps.find((a) => a.id === name);\n const port = appInfo?.port;\n // The scaffolded app is always a *different* app from the host MCP\n // server, so anchor the deep link to the new app's own origin. A\n // relative path would otherwise be prefixed with the current request\n // origin and land on the wrong app. Fall back to the relative path\n // only if the gateway hasn't reported the new app's URL yet.\n const relDeepLink = buildDeepLink({ app: name, view: \"home\" });\n const deepLink = appInfo?.url\n ? `${appInfo.url.replace(/\\/+$/, \"\")}${relDeepLink}`\n : relDeepLink;\n\n return {\n name,\n template,\n created: !alreadyExisted,\n reused: alreadyExisted,\n port,\n url: appInfo?.url,\n gatewayUrl: ws.gatewayUrl,\n deepLink,\n };\n },\n link: ({ result }) => {\n if (!result || typeof result !== \"object\") return null;\n const r = result as { deepLink?: string; name?: string };\n if (!r.deepLink) return null;\n return {\n url: r.deepLink,\n label: `Open ${r.name ?? \"app\"}`,\n view: \"home\",\n };\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Registry\n// ---------------------------------------------------------------------------\n\n/**\n * Build the generic cross-app builtin tool registry. Called by\n * `createMCPServerForRequest`; the result is merged UNDER the config's\n * actions so template actions of the same name win.\n */\nexport function getBuiltinCrossAppTools(\n config: MCPConfig,\n): Record<string, ActionEntry> {\n return {\n list_apps: listAppsTool(),\n open_app: openAppTool(config),\n ask_app: askAppTool(config),\n create_workspace_app: createWorkspaceAppTool(),\n list_templates: listTemplatesTool(),\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"builtin-tools.js","sourceRoot":"","sources":["../../src/mcp/builtin-tools.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAGH,OAAO,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AAEvD,OAAO,EAAE,YAAY,EAAe,MAAM,oBAAoB,CAAC;AAU/D;;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AC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,GAAG,WAAW,EAAE;gBACpD,CAAC,CAAC,WAAW,CAAC;YAEhB,OAAO;gBACL,IAAI;gBACJ,QAAQ;gBACR,OAAO,EAAE,CAAC,cAAc;gBACxB,MAAM,EAAE,cAAc;gBACtB,IAAI;gBACJ,GAAG,EAAE,OAAO,EAAE,GAAG;gBACjB,UAAU,EAAE,EAAE,CAAC,UAAU;gBACzB,QAAQ;aACT,CAAC;QACJ,CAAC;QACD,IAAI,EAAE,CAAC,EAAE,MAAM,EAAE,EAAE,EAAE;YACnB,IAAI,CAAC,MAAM,IAAI,OAAO,MAAM,KAAK,QAAQ;gBAAE,OAAO,IAAI,CAAC;YACvD,MAAM,CAAC,GAAG,MAA8C,CAAC;YACzD,IAAI,CAAC,CAAC,CAAC,QAAQ;gBAAE,OAAO,IAAI,CAAC;YAC7B,OAAO;gBACL,GAAG,EAAE,CAAC,CAAC,QAAQ;gBACf,KAAK,EAAE,QAAQ,CAAC,CAAC,IAAI,IAAI,KAAK,EAAE;gBAChC,IAAI,EAAE,MAAM;aACb,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC;AAED,8EAA8E;AAC9E,WAAW;AACX,8EAA8E;AAE9E;;;;GAIG;AACH,MAAM,UAAU,uBAAuB,CACrC,MAAiB;IAEjB,OAAO;QACL,SAAS,EAAE,YAAY,CAAC,MAAM,CAAC;QAC/B,QAAQ,EAAE,WAAW,CAAC,MAAM,CAAC;QAC7B,OAAO,EAAE,UAAU,CAAC,MAAM,CAAC;QAC3B,oBAAoB,EAAE,sBAAsB,EAAE;QAC9C,cAAc,EAAE,iBAAiB,EAAE;KACpC,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Generic cross-app MCP tools — a stable verb set every external agent gets\n * regardless of which template it is talking to.\n *\n * These are merged into the MCP action registry by\n * `createMCPServerForRequest` (see `build-server.ts`). **Precedence: template\n * actions win.** If a template defines an action named `list_apps` /\n * `open_app` / `ask_app` / `create_workspace_app` / `list_templates`, the\n * template's `ActionEntry` overwrites the builtin of the same name. This is\n * the same template-over-framework precedence `autoDiscoverActions` uses.\n *\n * | Tool | Side effects | Returns |\n * | --------------------- | ------------ | ---------------------------------------- |\n * | `list_apps` | none | `{ apps: [{ id, url, running }] }` |\n * | `open_app` | none | `{ url }` (+ deep-link `link`) |\n * | `ask_app` | agent loop | `{ app, routedVia, response }` |\n * | `create_workspace_app`| scaffolds | `{ name, url, port, deepLink }` (+ link) |\n *\n * `open_app` / `create_workspace_app` return an **absolute** URL on the\n * *target* app's origin when it differs from this app (so a workspace link\n * lands in the right app), and a relative path for the same app / standalone.\n * `ask_app` routes to a *different* workspace app over A2A when possible and\n * reports `routedVia: \"a2a\"`; otherwise it answers locally\n * (`routedVia: \"local\"`) and never falsely claims cross-app delegation.\n * | `list_templates` | none | `{ templates: [...] }` (allow-list only) |\n *\n * Node-only at call time (workspace resolution + scaffolding use `fs`), but\n * the module has no top-level Node imports so it bundles fine alongside\n * `mountMCP` — the Node bits are dynamically imported inside `run()`.\n */\n\nimport type { ActionEntry } from \"../agent/production-agent.js\";\nimport { buildDeepLink } from \"../server/deep-link.js\";\nimport type { MCPConfig } from \"./build-server.js\";\nimport { fetchOrgApps, type OrgApp } from \"./org-directory.js\";\n\nimport type { ActionTool } from \"../agent/types.js\";\n\n/** Flat map of param name → JSON-schema property. */\ntype Params = Record<\n string,\n { type: string; description?: string; enum?: string[] }\n>;\n\n/**\n * Build an `ActionTool`. `parameters` is wrapped in the\n * `{ type:\"object\", properties, required }` shape `createMCPServerForRequest`\n * forwards verbatim as the MCP tool `inputSchema`.\n */\nfunction tool(\n description: string,\n parameters?: Params,\n required?: string[],\n): ActionTool {\n if (!parameters) return { description };\n return {\n description,\n parameters: {\n type: \"object\",\n properties: parameters,\n ...(required && required.length ? { required } : {}),\n },\n };\n}\n\n/**\n * The canonical app id this MCP server is mounted for. `MCPConfig.appId` is\n * authoritative; fall back to lowercasing `name` (which is the capitalized\n * app id at every call site) for back-compat with configs that predate the\n * `appId` field.\n */\nfunction currentAppId(config: MCPConfig): string {\n return (config.appId || config.name || \"app\").toLowerCase();\n}\n\n/**\n * Resolve the absolute origin of a *target* workspace app (e.g.\n * `http://127.0.0.1:8101`) so cross-app deep links / A2A calls point at the\n * right app instead of the current request's origin. Reuses the same\n * workspace resolution `list_apps` / the stdio proxy use.\n *\n * Returns `null` when:\n * - the target is the current app (caller should keep relative behavior),\n * - there is no workspace info (standalone / single app), or\n * - the target app is unknown.\n */\nasync function resolveTargetAppOrigin(\n config: MCPConfig,\n targetAppId: string,\n): Promise<{ origin: string; id: string } | null> {\n const target = targetAppId.trim().toLowerCase();\n if (!target || target === currentAppId(config)) return null;\n try {\n const { resolveWorkspace } = await import(\"./workspace-resolve.js\");\n const ws = await resolveWorkspace();\n if (!ws.isWorkspace) return null;\n const match = ws.apps.find((a) => a.id.toLowerCase() === target);\n if (!match) return null;\n return { origin: match.url, id: match.id };\n } catch {\n return null;\n }\n}\n\n// ---------------------------------------------------------------------------\n// list_apps\n// ---------------------------------------------------------------------------\n\nfunction listAppsTool(config: MCPConfig): ActionEntry {\n return {\n tool: tool(\n \"List the workspace apps and their URLs. Use this to discover which \" +\n \"apps exist before opening or asking one. In a single-app project \" +\n \"this returns just that app. When an org directory is configured \" +\n \"this also includes the org's deployed sibling apps.\",\n ),\n readOnly: true,\n parallelSafe: true,\n run: async () => {\n const { resolveWorkspace } = await import(\"./workspace-resolve.js\");\n const ws = await resolveWorkspace();\n\n interface AppEntry {\n id: string;\n url: string;\n port: number | undefined;\n running: boolean;\n source: \"workspace\" | \"org-directory\";\n }\n\n const apps: AppEntry[] = ws.apps.map((a) => ({\n id: a.id,\n url: a.url,\n port: a.port as number | undefined,\n running: a.running,\n source: \"workspace\",\n }));\n const seenIds = new Set(apps.map((a) => a.id.toLowerCase()));\n const seenOrigins = new Set(apps.map((a) => a.url.replace(/\\/+$/, \"\")));\n\n // Merge the org directory's deployed sibling apps. Inactive (no env)\n // or any failure ⇒ fetchOrgApps() returns [] and this is a no-op, so\n // the existing local/workspace behavior is preserved exactly.\n const orgApps = await fetchOrgApps({\n selfId: currentAppId(config),\n }).catch(() => [] as OrgApp[]);\n for (const oa of orgApps) {\n const idKey = oa.id.toLowerCase();\n const originKey = oa.url.replace(/\\/+$/, \"\");\n // Dedupe by id OR origin — a workspace app already listed wins.\n if (seenIds.has(idKey) || seenOrigins.has(originKey)) continue;\n seenIds.add(idKey);\n seenOrigins.add(originKey);\n apps.push({\n id: oa.id,\n url: oa.url,\n port: undefined,\n running: true,\n source: \"org-directory\",\n });\n }\n\n return {\n workspace: ws.isWorkspace,\n gatewayUrl: ws.gatewayUrl,\n apps,\n };\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// open_app\n// ---------------------------------------------------------------------------\n\nfunction openAppTool(config: MCPConfig): ActionEntry {\n return {\n tool: tool(\n \"Build a deep link that opens an app at a specific view/record. No side \" +\n \"effects — returns a URL the user can click to land in the running UI. \" +\n 'After calling, surface the returned \"Open in … →\" link to the user.',\n {\n app: { type: \"string\", description: \"App id, e.g. 'mail'\" },\n view: {\n type: \"string\",\n description: \"Target view, e.g. 'inbox' (maps to navigate command)\",\n },\n params: {\n type: \"object\",\n description:\n \"Optional record-focus / filter params, e.g. { threadId: 'abc' }\",\n },\n },\n [\"app\", \"view\"],\n ),\n readOnly: true,\n parallelSafe: true,\n run: async (args: Record<string, any>) => {\n const app = String(args.app ?? \"\").trim();\n const view = String(args.view ?? \"\").trim();\n if (!app || !view) {\n throw new Error(\"open_app requires both 'app' and 'view'.\");\n }\n let params: Record<string, string | number | boolean> | undefined;\n const raw = args.params;\n if (raw && typeof raw === \"object\") {\n params = raw as Record<string, string | number | boolean>;\n } else if (typeof raw === \"string\" && raw.trim()) {\n try {\n params = JSON.parse(raw);\n } catch {\n params = undefined;\n }\n }\n const relUrl = buildDeepLink({ app, view, params });\n\n // Cross-app target in a workspace: resolve the TARGET app's origin and\n // return an absolute URL. Otherwise the MCP layer would prefix the\n // relative path with the CURRENT request origin, landing the user in\n // the wrong app (e.g. open_app({app:\"calendar\"}) served from Mail).\n // Same-app / standalone keeps the relative path (current behavior).\n const targetApp = await resolveTargetAppOrigin(config, app);\n const url = targetApp\n ? `${targetApp.origin.replace(/\\/+$/, \"\")}${relUrl}`\n : relUrl;\n\n return { app, view, url };\n },\n link: ({ result }) => {\n if (!result || typeof result !== \"object\") return null;\n const r = result as { url?: string; app?: string; view?: string };\n if (!r.url) return null;\n return {\n url: r.url,\n label: `Open ${r.app ?? \"app\"}`,\n view: r.view,\n };\n },\n };\n}\n\n/**\n * Route an `ask_app` message to a *different* app's agent over A2A. Shared by\n * the workspace-resolved path and the org-directory-resolved path so the A2A\n * call logic is not duplicated. `origin` is the target app's A2A base\n * (workspace dev origin or the directory's `a2aUrl`); `id` is reported back.\n *\n * Throws on failure so the caller can be honest — it never falls back to this\n * app's agent and pretends it was the target.\n */\nasync function routeAskOverA2A(\n origin: string,\n id: string,\n message: string,\n): Promise<{ app: string; routedVia: \"a2a\"; response: string }> {\n const { callAgent } = await import(\"../a2a/client.js\");\n const { resolveA2ACallerAuth } = await import(\"../a2a/caller-auth.js\");\n // The MCP handler runs inside `runWithRequestContext`, so this is the\n // verified caller identity and org scope. Reuse the same auth resolver as\n // org-directory discovery so the directory lookup and actual A2A call are\n // scoped the same way.\n const auth = await resolveA2ACallerAuth();\n const response = await callAgent(origin, message, {\n apiKey: auth.apiKey,\n userEmail: auth.userEmail,\n orgDomain: auth.orgDomain,\n orgSecret: auth.orgSecret,\n // Bound the wait — cross-app A2A polls async by default.\n timeoutMs: 5 * 60_000,\n });\n return { app: id, routedVia: \"a2a\", response };\n}\n\n// ---------------------------------------------------------------------------\n// ask_app\n// ---------------------------------------------------------------------------\n\nfunction askAppTool(config: MCPConfig): ActionEntry {\n return {\n tool: tool(\n \"Send a natural-language message to an app's AI agent and get its \" +\n \"response. Use for complex, multi-step tasks needing the agent's \" +\n \"reasoning and full app context. In a single-app project the 'app' \" +\n \"param is optional (defaults to this app). When 'app' names a \" +\n \"different workspace app it is routed there over A2A; the result's \" +\n \"'routedVia' field reports whether it ran cross-app or locally.\",\n {\n app: {\n type: \"string\",\n description: \"App id to route to (optional in a single-app project)\",\n },\n message: {\n type: \"string\",\n description: \"The message to send to the app's agent\",\n },\n },\n [\"message\"],\n ),\n run: async (args: Record<string, any>) => {\n const message = String(args.message ?? \"\").trim();\n if (!message) throw new Error(\"ask_app requires a 'message'.\");\n const requestedApp = String(args.app ?? \"\").trim();\n const selfId = currentAppId(config);\n\n // Cross-app: the caller named a *different* workspace app. Route the\n // message to THAT app's agent over A2A (its `/_agent-native/a2a`\n // endpoint runs the real agent loop with JWT identity) rather than\n // silently answering from this app's agent and claiming delegation.\n const targetApp = await resolveTargetAppOrigin(config, requestedApp);\n if (targetApp) {\n try {\n return await routeAskOverA2A(targetApp.origin, targetApp.id, message);\n } catch (err: any) {\n // Be honest: routing was attempted and failed — do NOT fall back to\n // this app's agent and pretend it was the target.\n throw new Error(\n `Failed to route ask_app to \"${targetApp.id}\" via A2A: ` +\n `${err?.message ?? err}`,\n );\n }\n }\n\n // Not a known local/workspace app — try the org directory. When a\n // directory is configured and the requested app is one of the org's\n // deployed sibling apps, route to it over A2A (same path as above,\n // against its `a2aUrl`). Inactive directory / any failure ⇒ orgApps is\n // [] and this is skipped, preserving the exact local-only behavior.\n if (requestedApp && requestedApp.toLowerCase() !== selfId) {\n const orgApps = await fetchOrgApps({ selfId }).catch(\n () => [] as OrgApp[],\n );\n const dirMatch = orgApps.find(\n (a) => a.id === requestedApp.toLowerCase(),\n );\n if (dirMatch) {\n try {\n return await routeAskOverA2A(dirMatch.a2aUrl, dirMatch.id, message);\n } catch (err: any) {\n throw new Error(\n `Failed to route ask_app to \"${dirMatch.id}\" via A2A ` +\n `(org directory): ${err?.message ?? err}`,\n );\n }\n }\n }\n\n // Same app (or no workspace / unknown target): answer locally with this\n // app's own ask-agent handler — the same entry point the HTTP MCP mount\n // + A2A use, so there is no second agent runner.\n if (!config.askAgent) {\n throw new Error(\n \"This app does not expose an agent (no ask-agent handler).\",\n );\n }\n\n // If the caller named an app we couldn't route to (unknown id, or no\n // workspace), say so honestly instead of claiming we reached it.\n const unresolved =\n !!requestedApp && requestedApp.toLowerCase() !== selfId;\n const response = await config.askAgent(message);\n return {\n app: selfId,\n routedVia: \"local\",\n ...(unresolved\n ? {\n note:\n `Requested app \"${requestedApp}\" is not a reachable workspace ` +\n `app; answered with this app (\"${selfId}\") instead.`,\n }\n : {}),\n response,\n };\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// list_templates\n// ---------------------------------------------------------------------------\n\nfunction listTemplatesTool(): ActionEntry {\n return {\n tool: tool(\n \"List the first-party templates that can be scaffolded into a workspace \" +\n \"(allow-listed templates only).\",\n ),\n readOnly: true,\n parallelSafe: true,\n run: async () => {\n const { visibleTemplates } = await import(\"../cli/templates-meta.js\");\n return {\n templates: visibleTemplates().map((t) => ({\n name: t.name,\n label: t.label,\n hint: t.hint,\n })),\n };\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// create_workspace_app\n// ---------------------------------------------------------------------------\n\nfunction createWorkspaceAppTool(): ActionEntry {\n return {\n tool: tool(\n \"Scaffold a new app into the current workspace from an allow-listed \" +\n \"template, then return a deep link to open it. Idempotent: if an app \" +\n \"with that name already exists it is reused. After calling, surface \" +\n 'the returned \"Open … →\" link to the user.',\n {\n name: {\n type: \"string\",\n description: \"New app id (directory under apps/), e.g. 'mymail'\",\n },\n template: {\n type: \"string\",\n description:\n \"Template to scaffold from — must be allow-listed (see list_templates)\",\n },\n },\n [\"name\", \"template\"],\n ),\n run: async (args: Record<string, any>) => {\n const name = String(args.name ?? \"\").trim();\n const template = String(args.template ?? \"\").trim();\n if (!name || !template) {\n throw new Error(\n \"create_workspace_app requires both 'name' and 'template'.\",\n );\n }\n\n // Enforce the strict public template allow-list. The authoritative,\n // dependency-free source inside @agent-native/core is cli/templates-meta\n // (kept in sync with packages/shared-app-config/templates.ts; CI guard).\n const { visibleTemplates } = await import(\"../cli/templates-meta.js\");\n const allowed = new Set(visibleTemplates().map((t) => t.name));\n if (!allowed.has(template)) {\n throw new Error(\n `Template \"${template}\" is not allow-listed. Allowed: ${[...allowed]\n .sort()\n .join(\", \")}`,\n );\n }\n\n const { findWorkspaceRoot, resolveWorkspace } =\n await import(\"./workspace-resolve.js\");\n const fs = await import(\"node:fs\");\n const path = await import(\"node:path\");\n\n const root = findWorkspaceRoot(process.cwd());\n if (!root) {\n throw new Error(\n \"Not inside a workspace. create_workspace_app only works in a \" +\n \"multi-app workspace (run from the workspace root).\",\n );\n }\n\n const appDir = path.join(root, \"apps\", name);\n const alreadyExisted = fs.existsSync(appDir);\n\n if (!alreadyExisted) {\n // Reuse the CLI scaffolder directly (no second `agent-native`\n // subprocess). `addAppToWorkspace(name, { template })` takes the\n // non-interactive single-template path when name + one template are\n // given. Run it from the workspace root so detectWorkspace resolves.\n const prevCwd = process.cwd();\n try {\n process.chdir(root);\n const { addAppToWorkspace } = await import(\"../cli/create.js\");\n await addAppToWorkspace(name, { template, noInstall: true });\n } finally {\n try {\n process.chdir(prevCwd);\n } catch {\n // best-effort cwd restore\n }\n }\n }\n\n // The workspace gateway auto-detects new apps/* dirs (fs.watch +\n // 2s sync) and lazily boots the dev server on first request, so we\n // don't spawn vite ourselves — opening the deep link warms it. Resolve\n // the port the gateway will use so we can report it.\n const ws = await resolveWorkspace(root);\n const appInfo = ws.apps.find((a) => a.id === name);\n const port = appInfo?.port;\n // The scaffolded app is always a *different* app from the host MCP\n // server, so anchor the deep link to the new app's own origin. A\n // relative path would otherwise be prefixed with the current request\n // origin and land on the wrong app. Fall back to the relative path\n // only if the gateway hasn't reported the new app's URL yet.\n const relDeepLink = buildDeepLink({ app: name, view: \"home\" });\n const deepLink = appInfo?.url\n ? `${appInfo.url.replace(/\\/+$/, \"\")}${relDeepLink}`\n : relDeepLink;\n\n return {\n name,\n template,\n created: !alreadyExisted,\n reused: alreadyExisted,\n port,\n url: appInfo?.url,\n gatewayUrl: ws.gatewayUrl,\n deepLink,\n };\n },\n link: ({ result }) => {\n if (!result || typeof result !== \"object\") return null;\n const r = result as { deepLink?: string; name?: string };\n if (!r.deepLink) return null;\n return {\n url: r.deepLink,\n label: `Open ${r.name ?? \"app\"}`,\n view: \"home\",\n };\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Registry\n// ---------------------------------------------------------------------------\n\n/**\n * Build the generic cross-app builtin tool registry. Called by\n * `createMCPServerForRequest`; the result is merged UNDER the config's\n * actions so template actions of the same name win.\n */\nexport function getBuiltinCrossAppTools(\n config: MCPConfig,\n): Record<string, ActionEntry> {\n return {\n list_apps: listAppsTool(config),\n open_app: openAppTool(config),\n ask_app: askAppTool(config),\n create_workspace_app: createWorkspaceAppTool(),\n list_templates: listTemplatesTool(),\n };\n}\n"]}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `/_agent-native/mcp/connect` — frictionless external-agent connection.
|
|
3
|
+
*
|
|
4
|
+
* A logged-in user on a deployed agent-native app (e.g. mail.agent-native.com)
|
|
5
|
+
* mints a per-user, scoped, revocable MCP bearer token WITHOUT ever copying a
|
|
6
|
+
* shared deployment secret. Two surfaces:
|
|
7
|
+
*
|
|
8
|
+
* 1. Browser — `GET /connect` renders a minimal in-app page (same inline
|
|
9
|
+
* HTML approach as the auth pages). The Authorize button POSTs to
|
|
10
|
+
* `/connect/token`, then shows the ready-to-paste `.mcp.json` entry, the
|
|
11
|
+
* `agent-native connect <origin>` one-liner, and the user's existing
|
|
12
|
+
* tokens with Revoke buttons.
|
|
13
|
+
* 2. CLI — an OAuth-2.0-device-authorization-style flow:
|
|
14
|
+
* POST /connect/device/start (unauth) → device_code + user_code
|
|
15
|
+
* GET /connect?user_code=… (browser) → user signs in & approves
|
|
16
|
+
* POST /connect/device/authorize (session) → binds user to the code
|
|
17
|
+
* POST /connect/device/poll (unauth) → mints + returns the token
|
|
18
|
+
*
|
|
19
|
+
* The minted token reuses the existing A2A signer (`signA2AToken`) — no new
|
|
20
|
+
* crypto. We only add a random `jti` + `scope: "mcp-connect"` claim so it can
|
|
21
|
+
* be revoked. `verifyAuth` already verifies A2A_SECRET JWTs and extracts
|
|
22
|
+
* `sub`/`org_domain`, so a minted token works against `/_agent-native/mcp`
|
|
23
|
+
* with no verify changes for the happy path (the revoke check is the only
|
|
24
|
+
* addition there).
|
|
25
|
+
*
|
|
26
|
+
* Node-only (crypto + the A2A signer), bundled alongside the other framework
|
|
27
|
+
* routes. Dialect-agnostic SQL lives in `connect-store.ts`.
|
|
28
|
+
*/
|
|
29
|
+
import type { H3Event } from "h3";
|
|
30
|
+
export interface McpConnectRouteOptions {
|
|
31
|
+
/** App id (directory under apps/, e.g. `mail`). Used for the server name. */
|
|
32
|
+
appId?: string;
|
|
33
|
+
/** Human app name shown on the connect page. */
|
|
34
|
+
appName?: string;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Handle a `/_agent-native/mcp/connect[...]` request. `subpath` is the part
|
|
38
|
+
* after `/connect` (empty string = the page itself, otherwise e.g.
|
|
39
|
+
* `/token`, `/device/start`). The core-routes-plugin computes it from the
|
|
40
|
+
* stripped event path so this module stays mount-agnostic.
|
|
41
|
+
*/
|
|
42
|
+
export declare function handleMcpConnect(event: H3Event, subpath: string, options?: McpConnectRouteOptions): Promise<Response>;
|
|
43
|
+
//# sourceMappingURL=connect-route.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"connect-route.d.ts","sourceRoot":"","sources":["../../src/mcp/connect-route.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AAEH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,IAAI,CAAC;AA+BlC,MAAM,WAAW,sBAAsB;IACrC,6EAA6E;IAC7E,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,gDAAgD;IAChD,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAufD;;;;;GAKG;AACH,wBAAsB,gBAAgB,CACpC,KAAK,EAAE,OAAO,EACd,OAAO,EAAE,MAAM,EACf,OAAO,GAAE,sBAA2B,GACnC,OAAO,CAAC,QAAQ,CAAC,CAoPnB"}
|