@agent-native/core 0.18.0 → 0.18.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/dist/mcp/build-server.d.ts +20 -3
- package/dist/mcp/build-server.d.ts.map +1 -1
- package/dist/mcp/build-server.js +90 -15
- package/dist/mcp/build-server.js.map +1 -1
- package/dist/mcp/builtin-tools.d.ts +8 -1
- package/dist/mcp/builtin-tools.d.ts.map +1 -1
- package/dist/mcp/builtin-tools.js +115 -13
- package/dist/mcp/builtin-tools.js.map +1 -1
- package/dist/mcp/server.d.ts.map +1 -1
- package/dist/mcp/server.js +23 -4
- package/dist/mcp/server.js.map +1 -1
- package/dist/mcp/stdio.d.ts.map +1 -1
- package/dist/mcp/stdio.js +1 -0
- package/dist/mcp/stdio.js.map +1 -1
- package/dist/server/agent-chat-plugin.d.ts.map +1 -1
- package/dist/server/agent-chat-plugin.js +1 -0
- package/dist/server/agent-chat-plugin.js.map +1 -1
- package/dist/server/auth.d.ts.map +1 -1
- package/dist/server/auth.js +46 -19
- package/dist/server/auth.js.map +1 -1
- package/dist/server/open-route.d.ts.map +1 -1
- package/dist/server/open-route.js +36 -5
- package/dist/server/open-route.js.map +1 -1
- package/dist/server/request-context.d.ts +8 -0
- package/dist/server/request-context.d.ts.map +1 -1
- package/dist/server/request-context.js.map +1 -1
- package/package.json +1 -1
|
@@ -21,6 +21,15 @@ import type { ActionEntry } from "../agent/production-agent.js";
|
|
|
21
21
|
export interface MCPConfig {
|
|
22
22
|
/** App name shown in MCP server info */
|
|
23
23
|
name: string;
|
|
24
|
+
/**
|
|
25
|
+
* Canonical app id (directory under `apps/`, e.g. `mail`) this MCP server
|
|
26
|
+
* is mounted for. Optional & back-compat: when omitted the builtin
|
|
27
|
+
* cross-app tools fall back to lowercasing `name`. Used by `open_app` /
|
|
28
|
+
* `ask_app` / `create_workspace_app` to tell "this app" from a cross-app
|
|
29
|
+
* target so they resolve the *target* app's origin rather than echoing the
|
|
30
|
+
* current request origin.
|
|
31
|
+
*/
|
|
32
|
+
appId?: string;
|
|
24
33
|
/** App description */
|
|
25
34
|
description: string;
|
|
26
35
|
/** Version string (default "1.0.0") */
|
|
@@ -117,8 +126,11 @@ export declare function createMCPServerForRequest(config: MCPConfig, identity: M
|
|
|
117
126
|
export declare function getAccessTokens(): string[];
|
|
118
127
|
/**
|
|
119
128
|
* Verify the inbound auth header. Returns:
|
|
120
|
-
* - { authed: true, identity } when verified — `identity`
|
|
121
|
-
*
|
|
129
|
+
* - { authed: true, identity } when verified — `identity` is derived from
|
|
130
|
+
* the JWT (`sub` / `org_domain`) for JWT auth, or from the
|
|
131
|
+
* `AGENT_NATIVE_OWNER_EMAIL` env / `X-Agent-Native-Owner-Email` header
|
|
132
|
+
* for static-token auth (the `agent-native mcp install` flow). `identity`
|
|
133
|
+
* is undefined only for true dev-open with no owner hint.
|
|
122
134
|
* - { authed: false } on rejection.
|
|
123
135
|
*
|
|
124
136
|
* When A2A_SECRET is set we extract the JWT's `sub` (caller email) and
|
|
@@ -126,8 +138,13 @@ export declare function getAccessTokens(): string[];
|
|
|
126
138
|
* `runWithRequestContext({ userEmail, orgId })`. Without that wrap, the
|
|
127
139
|
* MCP endpoint loses tenant identity and downstream `accessFilter` /
|
|
128
140
|
* `resolveCredential` calls fall back to platform-wide defaults.
|
|
141
|
+
*
|
|
142
|
+
* `ownerEmailHeader` is the forwarded `X-Agent-Native-Owner-Email` value; it
|
|
143
|
+
* is consulted ONLY on the static-token / dev-open path (never to influence
|
|
144
|
+
* verified JWT identity), so the install flow runs tools as the configured
|
|
145
|
+
* owner instead of an unscoped anonymous caller.
|
|
129
146
|
*/
|
|
130
|
-
export declare function verifyAuth(authHeader: string | undefined): Promise<{
|
|
147
|
+
export declare function verifyAuth(authHeader: string | undefined, ownerEmailHeader?: string | undefined): Promise<{
|
|
131
148
|
authed: boolean;
|
|
132
149
|
identity?: MCPCallerIdentity;
|
|
133
150
|
}>;
|
|
@@ -1 +1 @@
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AC,EACzB,MAAM,EAAE,GAAG,EACX,IAAI,EAAE,cAAc,GAAG,SAAS,GAC/B;IACD,KAAK,CAAC,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC;IACvC,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACjC,CAsBA;AA2BD;;;;;;;GAOG;AACH,wBAAsB,yBAAyB,CAC7C,MAAM,EAAE,SAAS,EACjB,QAAQ,EAAE,iBAAiB,GAAG,SAAS,EACvC,WAAW,CAAC,EAAE,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IA8J7B;AAOD,wBAAgB,eAAe,IAAI,MAAM,EAAE,CAc1C;AAyCD;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAsB,UAAU,CAC9B,UAAU,EAAE,MAAM,GAAG,SAAS,EAC9B,gBAAgB,CAAC,EAAE,MAAM,GAAG,SAAS,GACpC,OAAO,CAAC;IAAE,MAAM,EAAE,OAAO,CAAC;IAAC,QAAQ,CAAC,EAAE,iBAAiB,CAAA;CAAE,CAAC,CAiD5D;AAED,wBAAsB,sBAAsB,CAC1C,SAAS,EAAE,MAAM,GAAG,SAAS,GAC5B,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAS7B"}
|
package/dist/mcp/build-server.js
CHANGED
|
@@ -90,21 +90,43 @@ export async function createMCPServerForRequest(config, identity, requestMeta) {
|
|
|
90
90
|
// The action set the request handlers operate on = template actions +
|
|
91
91
|
// generic cross-app builtins (template wins on name collision).
|
|
92
92
|
const actions = mergeBuiltinTools(config);
|
|
93
|
+
// Resolve the effective caller identity. JWT / header-derived identity
|
|
94
|
+
// (passed by `mountMCP` via `verifyAuth`) wins. When the caller passed no
|
|
95
|
+
// identity — the stdio **standalone** path — fall back to the
|
|
96
|
+
// `AGENT_NATIVE_OWNER_EMAIL` env the `agent-native mcp install` flow writes
|
|
97
|
+
// into the `agent-native mcp serve` process env, so standalone tool runs are
|
|
98
|
+
// tenant-scoped to the configured owner instead of running unscoped. Stays
|
|
99
|
+
// undefined for true dev-open (no token, no secret, no owner) — behavior
|
|
100
|
+
// there is unchanged.
|
|
101
|
+
const ownerFromEnv = process.env.AGENT_NATIVE_OWNER_EMAIL?.trim();
|
|
102
|
+
const effectiveIdentity = identity ??
|
|
103
|
+
(ownerFromEnv
|
|
104
|
+
? { userEmail: ownerFromEnv, orgDomain: undefined }
|
|
105
|
+
: undefined);
|
|
93
106
|
// Resolve orgId once per request (DB lookup) so subsequent wraps are
|
|
94
|
-
// synchronous. The caller identity may be undefined for
|
|
95
|
-
//
|
|
96
|
-
//
|
|
97
|
-
//
|
|
98
|
-
const orgIdPromise = resolveOrgIdFromDomain(
|
|
107
|
+
// synchronous. The caller identity may be undefined for true dev-open —
|
|
108
|
+
// in that case we run with no userEmail/orgId, which makes downstream
|
|
109
|
+
// tools that require per-user scope return empty results rather than
|
|
110
|
+
// cross-tenant data (the safe default).
|
|
111
|
+
const orgIdPromise = resolveOrgIdFromDomain(effectiveIdentity?.orgDomain);
|
|
99
112
|
/**
|
|
100
|
-
* Wrap a callback in
|
|
113
|
+
* Wrap a callback in
|
|
114
|
+
* `runWithRequestContext({ userEmail, orgId, requestOrigin }, fn)`.
|
|
101
115
|
* Both the tools/list and tools/call handlers go through this so
|
|
102
116
|
* downstream `accessFilter`, `resolveCredential`, and per-user MCP
|
|
103
|
-
* visibility checks see the verified caller's identity.
|
|
117
|
+
* visibility checks see the verified caller's identity. `requestOrigin`
|
|
118
|
+
* is the live server origin derived from the inbound request (same value
|
|
119
|
+
* used to absolutize deep links) so actions that build fetchable URLs
|
|
120
|
+
* (e.g. design `export-coding-handoff`'s signed raw-code URL) resolve the
|
|
121
|
+
* correct local-workspace origin instead of a prod/localhost fallback.
|
|
104
122
|
*/
|
|
105
123
|
async function withCallerContext(fn) {
|
|
106
124
|
const orgId = await orgIdPromise;
|
|
107
|
-
return runWithRequestContext({
|
|
125
|
+
return runWithRequestContext({
|
|
126
|
+
userEmail: effectiveIdentity?.userEmail,
|
|
127
|
+
orgId,
|
|
128
|
+
...(requestMeta?.origin ? { requestOrigin: requestMeta.origin } : {}),
|
|
129
|
+
}, fn);
|
|
108
130
|
}
|
|
109
131
|
// tools/list — return all actions + ask-agent meta-tool. Wrapped in the
|
|
110
132
|
// request context so per-user MCP visibility (mcp-client/visibility.ts)
|
|
@@ -212,10 +234,49 @@ export function getAccessTokens() {
|
|
|
212
234
|
}
|
|
213
235
|
return tokens;
|
|
214
236
|
}
|
|
237
|
+
/**
|
|
238
|
+
* Resolve the caller identity for a static-token (or dev-open) auth path.
|
|
239
|
+
*
|
|
240
|
+
* Static `ACCESS_TOKEN` / `ACCESS_TOKENS` auth carries no per-caller claims,
|
|
241
|
+
* so without this the MCP endpoint would run every tool with
|
|
242
|
+
* `userEmail === undefined` and per-user / per-org scoped actions
|
|
243
|
+
* (`accessFilter`, `resolveAccess`, `resolveCredential`) would return
|
|
244
|
+
* empty / wrong data. The `agent-native mcp install` flow writes
|
|
245
|
+
* `AGENT_NATIVE_OWNER_EMAIL` into the client config env and the stdio proxy
|
|
246
|
+
* forwards it as the `X-Agent-Native-Owner-Email` request header (see
|
|
247
|
+
* `mcp/stdio.ts#authHeaders`). We trust that owner hint *only* on the
|
|
248
|
+
* static-token path — JWT auth already carries a cryptographically verified
|
|
249
|
+
* `sub`, so the header is ignored there and never widens JWT scope.
|
|
250
|
+
*
|
|
251
|
+
* Precedence is server-trusted-first: the server process's
|
|
252
|
+
* `AGENT_NATIVE_OWNER_EMAIL` env (set out-of-band by the operator / deploy)
|
|
253
|
+
* ALWAYS wins, and a client-supplied `X-Agent-Native-Owner-Email` header is
|
|
254
|
+
* honored *only as a fallback when that env is unset*. A static `ACCESS_TOKEN`
|
|
255
|
+
* is a shared bearer secret; letting a request header override a
|
|
256
|
+
* server-configured owner would let anyone holding a leaked token act as any
|
|
257
|
+
* user. The header path remains for the single-tenant local-dev install flow
|
|
258
|
+
* where the app server process has no owner env and the token *is* the
|
|
259
|
+
* workspace secret; multi-tenant deployments must use A2A JWT (verified `sub`),
|
|
260
|
+
* not a static token, for per-user scope.
|
|
261
|
+
*
|
|
262
|
+
* Returns `undefined` when no owner email is available (true dev-open: no
|
|
263
|
+
* token, no secret, no owner) so behavior there stays unchanged.
|
|
264
|
+
*/
|
|
265
|
+
function deriveStaticTokenIdentity(ownerEmailHeader) {
|
|
266
|
+
const owner = process.env.AGENT_NATIVE_OWNER_EMAIL?.trim() ||
|
|
267
|
+
(typeof ownerEmailHeader === "string" && ownerEmailHeader.trim()) ||
|
|
268
|
+
"";
|
|
269
|
+
if (!owner)
|
|
270
|
+
return undefined;
|
|
271
|
+
return { userEmail: owner, orgDomain: undefined };
|
|
272
|
+
}
|
|
215
273
|
/**
|
|
216
274
|
* Verify the inbound auth header. Returns:
|
|
217
|
-
* - { authed: true, identity } when verified — `identity`
|
|
218
|
-
*
|
|
275
|
+
* - { authed: true, identity } when verified — `identity` is derived from
|
|
276
|
+
* the JWT (`sub` / `org_domain`) for JWT auth, or from the
|
|
277
|
+
* `AGENT_NATIVE_OWNER_EMAIL` env / `X-Agent-Native-Owner-Email` header
|
|
278
|
+
* for static-token auth (the `agent-native mcp install` flow). `identity`
|
|
279
|
+
* is undefined only for true dev-open with no owner hint.
|
|
219
280
|
* - { authed: false } on rejection.
|
|
220
281
|
*
|
|
221
282
|
* When A2A_SECRET is set we extract the JWT's `sub` (caller email) and
|
|
@@ -223,13 +284,22 @@ export function getAccessTokens() {
|
|
|
223
284
|
* `runWithRequestContext({ userEmail, orgId })`. Without that wrap, the
|
|
224
285
|
* MCP endpoint loses tenant identity and downstream `accessFilter` /
|
|
225
286
|
* `resolveCredential` calls fall back to platform-wide defaults.
|
|
287
|
+
*
|
|
288
|
+
* `ownerEmailHeader` is the forwarded `X-Agent-Native-Owner-Email` value; it
|
|
289
|
+
* is consulted ONLY on the static-token / dev-open path (never to influence
|
|
290
|
+
* verified JWT identity), so the install flow runs tools as the configured
|
|
291
|
+
* owner instead of an unscoped anonymous caller.
|
|
226
292
|
*/
|
|
227
|
-
export async function verifyAuth(authHeader) {
|
|
228
|
-
// No auth configured → allow (dev mode)
|
|
293
|
+
export async function verifyAuth(authHeader, ownerEmailHeader) {
|
|
294
|
+
// No auth configured → allow (dev mode). Still honour an owner hint
|
|
295
|
+
// (env or forwarded header) so the install flow stays tenant-scoped.
|
|
229
296
|
const accessTokens = getAccessTokens();
|
|
230
297
|
const hasA2ASecret = !!process.env.A2A_SECRET;
|
|
231
298
|
if (accessTokens.length === 0 && !hasA2ASecret) {
|
|
232
|
-
return {
|
|
299
|
+
return {
|
|
300
|
+
authed: true,
|
|
301
|
+
identity: deriveStaticTokenIdentity(ownerEmailHeader),
|
|
302
|
+
};
|
|
233
303
|
}
|
|
234
304
|
if (!authHeader?.startsWith("Bearer "))
|
|
235
305
|
return { authed: false };
|
|
@@ -253,9 +323,14 @@ export async function verifyAuth(authHeader) {
|
|
|
253
323
|
// Not a valid JWT — fall through to token check
|
|
254
324
|
}
|
|
255
325
|
}
|
|
256
|
-
// Try ACCESS_TOKEN / ACCESS_TOKENS exact match
|
|
326
|
+
// Try ACCESS_TOKEN / ACCESS_TOKENS exact match. Static tokens carry no
|
|
327
|
+
// per-caller claims, so derive identity from the forwarded owner-email
|
|
328
|
+
// hint (install flow) — otherwise tools would run unscoped.
|
|
257
329
|
if (accessTokens.length > 0 && accessTokens.includes(token)) {
|
|
258
|
-
return {
|
|
330
|
+
return {
|
|
331
|
+
authed: true,
|
|
332
|
+
identity: deriveStaticTokenIdentity(ownerEmailHeader),
|
|
333
|
+
};
|
|
259
334
|
}
|
|
260
335
|
return { authed: false };
|
|
261
336
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build-server.js","sourceRoot":"","sources":["../../src/mcp/build-server.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAGH,OAAO,EAAE,qBAAqB,E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E,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,yEAAyE;IACzE,IAAI,YAAY,CAAC,MAAM,GAAG,CAAC,IAAI,YAAY,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;QAC5D,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC;IAC1B,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 /** 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 orgId once per request (DB lookup) so subsequent wraps are\n // synchronous. The caller identity may be undefined for ACCESS_TOKEN\n // auth — in that case we run with no userEmail/orgId, which makes\n // downstream tools that require per-user scope return empty results\n // rather than cross-tenant data (the safe default).\n const orgIdPromise = resolveOrgIdFromDomain(identity?.orgDomain);\n\n /**\n * Wrap a callback in `runWithRequestContext({ userEmail, orgId }, 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.\n */\n async function withCallerContext<T>(fn: () => Promise<T>): Promise<T> {\n const orgId = await orgIdPromise;\n return runWithRequestContext(\n { userEmail: identity?.userEmail, orgId },\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 * Verify the inbound auth header. Returns:\n * - { authed: true, identity } when verified — `identity` may be empty\n * when authed via a static ACCESS_TOKEN (no caller email available).\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 */\nexport async function verifyAuth(\n authHeader: string | undefined,\n): Promise<{ authed: boolean; identity?: MCPCallerIdentity }> {\n // No auth configured → allow (dev mode), but no identity to propagate.\n const accessTokens = getAccessTokens();\n const hasA2ASecret = !!process.env.A2A_SECRET;\n if (accessTokens.length === 0 && !hasA2ASecret) {\n return { authed: true };\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 (no per-caller identity).\n if (accessTokens.length > 0 && accessTokens.includes(token)) {\n return { authed: true };\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,qB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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"]}
|
|
@@ -13,8 +13,15 @@
|
|
|
13
13
|
* | --------------------- | ------------ | ---------------------------------------- |
|
|
14
14
|
* | `list_apps` | none | `{ apps: [{ id, url, running }] }` |
|
|
15
15
|
* | `open_app` | none | `{ url }` (+ deep-link `link`) |
|
|
16
|
-
* | `ask_app` | agent loop | `{ app, response }`
|
|
16
|
+
* | `ask_app` | agent loop | `{ app, routedVia, response }` |
|
|
17
17
|
* | `create_workspace_app`| scaffolds | `{ name, url, port, deepLink }` (+ link) |
|
|
18
|
+
*
|
|
19
|
+
* `open_app` / `create_workspace_app` return an **absolute** URL on the
|
|
20
|
+
* *target* app's origin when it differs from this app (so a workspace link
|
|
21
|
+
* lands in the right app), and a relative path for the same app / standalone.
|
|
22
|
+
* `ask_app` routes to a *different* workspace app over A2A when possible and
|
|
23
|
+
* reports `routedVia: "a2a"`; otherwise it answers locally
|
|
24
|
+
* (`routedVia: "local"`) and never falsely claims cross-app delegation.
|
|
18
25
|
* | `list_templates` | none | `{ templates: [...] }` (allow-list only) |
|
|
19
26
|
*
|
|
20
27
|
* Node-only at call time (workspace resolution + scaffolding use `fs`), but
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"builtin-tools.d.ts","sourceRoot":"","sources":["../../src/mcp/builtin-tools.ts"],"names":[],"mappings":"AAAA
|
|
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;AA+ZnD;;;;GAIG;AACH,wBAAgB,uBAAuB,CACrC,MAAM,EAAE,SAAS,GAChB,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,CAQ7B"}
|
|
@@ -13,8 +13,15 @@
|
|
|
13
13
|
* | --------------------- | ------------ | ---------------------------------------- |
|
|
14
14
|
* | `list_apps` | none | `{ apps: [{ id, url, running }] }` |
|
|
15
15
|
* | `open_app` | none | `{ url }` (+ deep-link `link`) |
|
|
16
|
-
* | `ask_app` | agent loop | `{ app, response }`
|
|
16
|
+
* | `ask_app` | agent loop | `{ app, routedVia, response }` |
|
|
17
17
|
* | `create_workspace_app`| scaffolds | `{ name, url, port, deepLink }` (+ link) |
|
|
18
|
+
*
|
|
19
|
+
* `open_app` / `create_workspace_app` return an **absolute** URL on the
|
|
20
|
+
* *target* app's origin when it differs from this app (so a workspace link
|
|
21
|
+
* lands in the right app), and a relative path for the same app / standalone.
|
|
22
|
+
* `ask_app` routes to a *different* workspace app over A2A when possible and
|
|
23
|
+
* reports `routedVia: "a2a"`; otherwise it answers locally
|
|
24
|
+
* (`routedVia: "local"`) and never falsely claims cross-app delegation.
|
|
18
25
|
* | `list_templates` | none | `{ templates: [...] }` (allow-list only) |
|
|
19
26
|
*
|
|
20
27
|
* Node-only at call time (workspace resolution + scaffolding use `fs`), but
|
|
@@ -39,6 +46,44 @@ function tool(description, parameters, required) {
|
|
|
39
46
|
},
|
|
40
47
|
};
|
|
41
48
|
}
|
|
49
|
+
/**
|
|
50
|
+
* The canonical app id this MCP server is mounted for. `MCPConfig.appId` is
|
|
51
|
+
* authoritative; fall back to lowercasing `name` (which is the capitalized
|
|
52
|
+
* app id at every call site) for back-compat with configs that predate the
|
|
53
|
+
* `appId` field.
|
|
54
|
+
*/
|
|
55
|
+
function currentAppId(config) {
|
|
56
|
+
return (config.appId || config.name || "app").toLowerCase();
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Resolve the absolute origin of a *target* workspace app (e.g.
|
|
60
|
+
* `http://127.0.0.1:8101`) so cross-app deep links / A2A calls point at the
|
|
61
|
+
* right app instead of the current request's origin. Reuses the same
|
|
62
|
+
* workspace resolution `list_apps` / the stdio proxy use.
|
|
63
|
+
*
|
|
64
|
+
* Returns `null` when:
|
|
65
|
+
* - the target is the current app (caller should keep relative behavior),
|
|
66
|
+
* - there is no workspace info (standalone / single app), or
|
|
67
|
+
* - the target app is unknown.
|
|
68
|
+
*/
|
|
69
|
+
async function resolveTargetAppOrigin(config, targetAppId) {
|
|
70
|
+
const target = targetAppId.trim().toLowerCase();
|
|
71
|
+
if (!target || target === currentAppId(config))
|
|
72
|
+
return null;
|
|
73
|
+
try {
|
|
74
|
+
const { resolveWorkspace } = await import("./workspace-resolve.js");
|
|
75
|
+
const ws = await resolveWorkspace();
|
|
76
|
+
if (!ws.isWorkspace)
|
|
77
|
+
return null;
|
|
78
|
+
const match = ws.apps.find((a) => a.id.toLowerCase() === target);
|
|
79
|
+
if (!match)
|
|
80
|
+
return null;
|
|
81
|
+
return { origin: match.url, id: match.id };
|
|
82
|
+
}
|
|
83
|
+
catch {
|
|
84
|
+
return null;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
42
87
|
// ---------------------------------------------------------------------------
|
|
43
88
|
// list_apps
|
|
44
89
|
// ---------------------------------------------------------------------------
|
|
@@ -68,7 +113,7 @@ function listAppsTool() {
|
|
|
68
113
|
// ---------------------------------------------------------------------------
|
|
69
114
|
// open_app
|
|
70
115
|
// ---------------------------------------------------------------------------
|
|
71
|
-
function openAppTool() {
|
|
116
|
+
function openAppTool(config) {
|
|
72
117
|
return {
|
|
73
118
|
tool: tool("Build a deep link that opens an app at a specific view/record. No side " +
|
|
74
119
|
"effects — returns a URL the user can click to land in the running UI. " +
|
|
@@ -104,7 +149,16 @@ function openAppTool() {
|
|
|
104
149
|
params = undefined;
|
|
105
150
|
}
|
|
106
151
|
}
|
|
107
|
-
const
|
|
152
|
+
const relUrl = buildDeepLink({ app, view, params });
|
|
153
|
+
// Cross-app target in a workspace: resolve the TARGET app's origin and
|
|
154
|
+
// return an absolute URL. Otherwise the MCP layer would prefix the
|
|
155
|
+
// relative path with the CURRENT request origin, landing the user in
|
|
156
|
+
// the wrong app (e.g. open_app({app:"calendar"}) served from Mail).
|
|
157
|
+
// Same-app / standalone keeps the relative path (current behavior).
|
|
158
|
+
const targetApp = await resolveTargetAppOrigin(config, app);
|
|
159
|
+
const url = targetApp
|
|
160
|
+
? `${targetApp.origin.replace(/\/+$/, "")}${relUrl}`
|
|
161
|
+
: relUrl;
|
|
108
162
|
return { app, view, url };
|
|
109
163
|
},
|
|
110
164
|
link: ({ result }) => {
|
|
@@ -129,7 +183,9 @@ function askAppTool(config) {
|
|
|
129
183
|
tool: tool("Send a natural-language message to an app's AI agent and get its " +
|
|
130
184
|
"response. Use for complex, multi-step tasks needing the agent's " +
|
|
131
185
|
"reasoning and full app context. In a single-app project the 'app' " +
|
|
132
|
-
"param is optional (defaults to this app)."
|
|
186
|
+
"param is optional (defaults to this app). When 'app' names a " +
|
|
187
|
+
"different workspace app it is routed there over A2A; the result's " +
|
|
188
|
+
"'routedVia' field reports whether it ran cross-app or locally.", {
|
|
133
189
|
app: {
|
|
134
190
|
type: "string",
|
|
135
191
|
description: "App id to route to (optional in a single-app project)",
|
|
@@ -144,18 +200,56 @@ function askAppTool(config) {
|
|
|
144
200
|
if (!message)
|
|
145
201
|
throw new Error("ask_app requires a 'message'.");
|
|
146
202
|
const requestedApp = String(args.app ?? "").trim();
|
|
147
|
-
|
|
148
|
-
//
|
|
149
|
-
//
|
|
150
|
-
//
|
|
151
|
-
//
|
|
152
|
-
|
|
203
|
+
const selfId = currentAppId(config);
|
|
204
|
+
// Cross-app: the caller named a *different* workspace app. Route the
|
|
205
|
+
// message to THAT app's agent over A2A (its `/_agent-native/a2a`
|
|
206
|
+
// endpoint runs the real agent loop with JWT identity) rather than
|
|
207
|
+
// silently answering from this app's agent and claiming delegation.
|
|
208
|
+
const targetApp = await resolveTargetAppOrigin(config, requestedApp);
|
|
209
|
+
if (targetApp) {
|
|
210
|
+
try {
|
|
211
|
+
const { callAgent } = await import("../a2a/client.js");
|
|
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
|
+
};
|
|
226
|
+
}
|
|
227
|
+
catch (err) {
|
|
228
|
+
// Be honest: routing was attempted and failed — do NOT fall back to
|
|
229
|
+
// this app's agent and pretend it was the target.
|
|
230
|
+
throw new Error(`Failed to route ask_app to "${targetApp.id}" via A2A: ` +
|
|
231
|
+
`${err?.message ?? err}`);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
// Same app (or no workspace / unknown target): answer locally with this
|
|
235
|
+
// app's own ask-agent handler — the same entry point the HTTP MCP mount
|
|
236
|
+
// + A2A use, so there is no second agent runner.
|
|
153
237
|
if (!config.askAgent) {
|
|
154
238
|
throw new Error("This app does not expose an agent (no ask-agent handler).");
|
|
155
239
|
}
|
|
240
|
+
// If the caller named an app we couldn't route to (unknown id, or no
|
|
241
|
+
// workspace), say so honestly instead of claiming we reached it.
|
|
242
|
+
const unresolved = !!requestedApp && requestedApp.toLowerCase() !== selfId;
|
|
156
243
|
const response = await config.askAgent(message);
|
|
157
244
|
return {
|
|
158
|
-
app:
|
|
245
|
+
app: selfId,
|
|
246
|
+
routedVia: "local",
|
|
247
|
+
...(unresolved
|
|
248
|
+
? {
|
|
249
|
+
note: `Requested app "${requestedApp}" is not a reachable workspace ` +
|
|
250
|
+
`app; answered with this app ("${selfId}") instead.`,
|
|
251
|
+
}
|
|
252
|
+
: {}),
|
|
159
253
|
response,
|
|
160
254
|
};
|
|
161
255
|
},
|
|
@@ -253,7 +347,15 @@ function createWorkspaceAppTool() {
|
|
|
253
347
|
const ws = await resolveWorkspace(root);
|
|
254
348
|
const appInfo = ws.apps.find((a) => a.id === name);
|
|
255
349
|
const port = appInfo?.port;
|
|
256
|
-
|
|
350
|
+
// The scaffolded app is always a *different* app from the host MCP
|
|
351
|
+
// server, so anchor the deep link to the new app's own origin. A
|
|
352
|
+
// relative path would otherwise be prefixed with the current request
|
|
353
|
+
// origin and land on the wrong app. Fall back to the relative path
|
|
354
|
+
// only if the gateway hasn't reported the new app's URL yet.
|
|
355
|
+
const relDeepLink = buildDeepLink({ app: name, view: "home" });
|
|
356
|
+
const deepLink = appInfo?.url
|
|
357
|
+
? `${appInfo.url.replace(/\/+$/, "")}${relDeepLink}`
|
|
358
|
+
: relDeepLink;
|
|
257
359
|
return {
|
|
258
360
|
name,
|
|
259
361
|
template,
|
|
@@ -290,7 +392,7 @@ function createWorkspaceAppTool() {
|
|
|
290
392
|
export function getBuiltinCrossAppTools(config) {
|
|
291
393
|
return {
|
|
292
394
|
list_apps: listAppsTool(),
|
|
293
|
-
open_app: openAppTool(),
|
|
395
|
+
open_app: openAppTool(config),
|
|
294
396
|
ask_app: askAppTool(config),
|
|
295
397
|
create_workspace_app: createWorkspaceAppTool(),
|
|
296
398
|
list_templates: listTemplatesTool(),
|