@agent-native/core 0.22.31 → 0.22.33

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/action.d.ts CHANGED
@@ -111,6 +111,13 @@ export interface ActionMcpAppConfig {
111
111
  * action and the app iframe can call it back through the host bridge.
112
112
  */
113
113
  visibility?: Array<"model" | "app">;
114
+ /**
115
+ * Rare escape hatch for MCP Apps chat hosts. By default OAuth callers with
116
+ * `mcp:apps` see the generic app tools (`open_app`, `list_apps`, etc.) so
117
+ * hosts do not ingest every action-specific UI resource. Set this only when
118
+ * this specific action must stay visible in that compact catalog.
119
+ */
120
+ compactCatalog?: boolean;
114
121
  }
115
122
  /** Schema definition for a single action parameter (legacy JSON schema style). */
116
123
  export interface ParameterSchema {
@@ -1 +1 @@
1
- {"version":3,"file":"action.d.ts","sourceRoot":"","sources":["../src/action.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAE9D,MAAM,WAAW,sBAAsB;IACrC,+DAA+D;IAC/D,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,4EAA4E;IAC5E,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAED;;;GAGG;AACH,qBAAa,oBAAqB,SAAQ,KAAK;IAC7C,QAAQ,CAAC,eAAe,QAAQ;IAChC,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC;gBAEjB,OAAO,EAAE,MAAM,EAAE,OAAO,GAAE,sBAA2B;CAMlE;AAED,wBAAgB,sBAAsB,CACpC,GAAG,EAAE,OAAO,GACX,GAAG,IAAI,oBAAoB,CAU7B;AAED,0CAA0C;AAC1C,MAAM,WAAW,gBAAgB;IAC/B,qEAAqE;IACrE,MAAM,CAAC,EAAE,KAAK,GAAG,MAAM,GAAG,KAAK,GAAG,QAAQ,CAAC;IAC3C,mFAAmF;IACn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gBACP,QAAQ,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC;YAC1B,CAAC;YAED,uEAAuE;YACvE,yEAAyE;YACzE,wCAAwC;YACxC,IAAI,QAAQ,GAAG,EAAE,CAAC;YAClB,IAAI,cAAc,EAAE,UAAU,EAAE,CAAC;gBAC/B,MAAM,QAAQ,GAAG,IAAI,GAAG,CAAC,cAAc,CAAC,QAAQ,IAAI,EAAE,CAAC,CAAC;gBACxD,MAAM,GAAG,GAAG,MAAM,CAAC,OAAO,CAAC,cAAc,CAAC,UAAU,CAAC;qBAClD,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,EAAE;oBACd,MAAM,IAAI,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC;oBACzC,MAAM,IAAI,GAAI,CAAuB,CAAC,IAAI,IAAI,KAAK,CAAC;oBACpD,OAAO,GAAG,CAAC,GAAG,IAAI,KAAK,IAAI,EAAE,CAAC;gBAChC,CAAC,CAAC;qBACD,IAAI,CAAC,IAAI,CAAC,CAAC;gBACd,IAAI,GAAG;oBACL,QAAQ,GAAG,gBAAgB,GAAG,wCAAwC,CAAC;YAC3E,CAAC;YAED,MAAM,IAAI,KAAK,CACb,+BAA+B,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,eAAe,QAAQ,IAAI,QAAQ,EAAE,CACrF,CAAC;QACJ,CAAC;QACD,OAAO,GAAG,CAAE,MAA8C,CAAC,KAAK,CAAC,CAAC;IACpE,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import type { ActionTool } from \"./agent/types.js\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\n\nexport interface AgentActionStopOptions {\n /** Optional stable code surfaced in run metadata and tests. */\n errorCode?: string;\n /** Optional short tool-result text. Defaults to the user-facing message. */\n toolResult?: string;\n}\n\n/**\n * Throw from an action when the agent should stop the current turn instead of\n * feeding the failure back to the model for another retry.\n */\nexport class AgentActionStopError extends Error {\n readonly agentNativeStop = true;\n readonly errorCode?: string;\n readonly toolResult?: string;\n\n constructor(message: string, options: AgentActionStopOptions = {}) {\n super(message);\n this.name = \"AgentActionStopError\";\n this.errorCode = options.errorCode;\n this.toolResult = options.toolResult;\n }\n}\n\nexport function isAgentActionStopError(\n err: unknown,\n): err is AgentActionStopError {\n return (\n err instanceof AgentActionStopError ||\n Boolean(\n err &&\n typeof err === \"object\" &&\n \"agentNativeStop\" in err &&\n (err as { agentNativeStop?: unknown }).agentNativeStop === true,\n )\n );\n}\n\n/** HTTP exposure config for an action. */\nexport interface ActionHttpConfig {\n /** HTTP method. Default: \"POST\". Use \"GET\" for read-only actions. */\n method?: \"GET\" | \"POST\" | \"PUT\" | \"DELETE\";\n /** Override route path under /_agent-native/actions/. Default: action filename. */\n path?: string;\n}\n\n/** Explicit opt-in metadata for public agent protocols such as MCP or A2A. */\nexport interface PublicAgentActionConfig {\n expose: boolean;\n readOnly: boolean;\n requiresAuth?: boolean;\n isConsequential?: boolean;\n title?: string;\n description?: string;\n}\n\n/** A deep link an external agent (MCP / A2A) can surface to the user so they\n * can open the produced/listed resource in the running app UI. */\nexport interface ActionDeepLink {\n /** App-relative path (e.g. `/_agent-native/open?app=mail&view=inbox&...`)\n * or an absolute URL. The MCP layer prefixes the request origin when this\n * is relative, and may rewrite it to the `agentnative://` desktop scheme. */\n url: string;\n /** Human-readable label, e.g. \"Open draft in Mail\". */\n label: string;\n /** Optional view hint (matches the `navigate` command `view`). */\n view?: string;\n}\n\n/** Builds a deep link from an action's args + result so external agents can\n * surface an \"Open in <app> →\" link. MUST be pure and synchronous — no I/O,\n * no awaits. Best-effort: a throw or null is swallowed and never fails the\n * tool call. See the `external-agents` skill. */\nexport type ActionLinkBuilder = (ctx: {\n args: Record<string, any>;\n result: any;\n}) => ActionDeepLink | null | undefined;\n\nexport const MCP_APP_EXTENSION_ID = \"io.modelcontextprotocol/ui\" as const;\nexport const MCP_APP_MIME_TYPE = \"text/html;profile=mcp-app\" as const;\nexport const MCP_APP_RESOURCE_URI_META_KEY = \"ui/resourceUri\" as const;\n\nexport interface ActionMcpAppCsp {\n connectDomains?: string[];\n resourceDomains?: string[];\n frameDomains?: string[];\n baseUriDomains?: string[];\n}\n\nexport type ActionMcpAppCspBuilder = (ctx: {\n actionName: string;\n appId?: string;\n requestOrigin?: string;\n}) => ActionMcpAppCsp | Promise<ActionMcpAppCsp>;\n\nexport interface ActionMcpAppPermissions {\n camera?: Record<string, never>;\n microphone?: Record<string, never>;\n geolocation?: Record<string, never>;\n clipboardWrite?: Record<string, never>;\n}\n\nexport interface ActionMcpAppResourceMeta {\n csp?: ActionMcpAppCsp | ActionMcpAppCspBuilder;\n permissions?: ActionMcpAppPermissions;\n domain?: string;\n prefersBorder?: boolean;\n}\n\nexport type ActionMcpAppHtmlBuilder = (ctx: {\n actionName: string;\n appId?: string;\n requestOrigin?: string;\n}) => string;\n\nexport interface ActionMcpAppResourceConfig {\n /** `ui://` URI. Defaults to `ui://<app>/<action-name>`. */\n uri?: string;\n /** MCP resource name. Defaults to the action name. */\n name?: string;\n title?: string;\n description?: string;\n /**\n * HTML5 document content for the MCP App resource. Keep this self-contained\n * or declare any external origins in `csp`.\n */\n html: string | ActionMcpAppHtmlBuilder;\n /** Defaults to the MCP Apps HTML MIME type. */\n mimeType?: typeof MCP_APP_MIME_TYPE;\n /** Extra resource/content metadata. `ui` is merged with the fields below. */\n _meta?: Record<string, unknown>;\n csp?: ActionMcpAppCsp | ActionMcpAppCspBuilder;\n permissions?: ActionMcpAppPermissions;\n domain?: string;\n prefersBorder?: boolean;\n}\n\nexport interface ActionMcpAppConfig {\n resource: ActionMcpAppResourceConfig;\n /**\n * MCP Apps tool visibility. Defaults to model + app so the LLM can call the\n * action and the app iframe can call it back through the host bridge.\n */\n visibility?: Array<\"model\" | \"app\">;\n}\n\n/** Schema definition for a single action parameter (legacy JSON schema style). */\nexport interface ParameterSchema {\n type: string;\n description?: string;\n enum?: string[];\n}\n\n/** Infer runtime parameter types from a legacy parameter schema map. */\ntype InferParams<T extends Record<string, ParameterSchema> | undefined> =\n T extends Record<string, ParameterSchema>\n ? { [K in keyof T]?: string }\n : Record<string, string>;\n\n// ---------------------------------------------------------------------------\n// Schema-based action options (new: Zod / Valibot / ArkType via Standard Schema)\n// ---------------------------------------------------------------------------\n\ninterface DefineActionWithSchema<\n TSchema extends StandardSchemaV1,\n TReturn = any,\n> {\n description: string;\n /** Standard Schema-compatible schema (Zod, Valibot, ArkType). Provides runtime\n * validation and full TypeScript type inference for `run()` args. The schema is\n * also converted to JSON Schema for the Claude API tool definition. */\n schema: TSchema;\n /** Legacy parameters — ignored when `schema` is provided. */\n parameters?: never;\n run: (\n args: StandardSchemaV1.InferOutput<TSchema>,\n ) => Promise<TReturn> | TReturn;\n http?: ActionHttpConfig | false;\n /** If true, the framework will NOT emit a screen-refresh change event after a\n * successful call. Auto-inferred as `true` when `http.method === \"GET\"`.\n * Only set this manually when you need to override the inference — e.g. a\n * POST action that only reads data but can't use GET for a protocol reason. */\n readOnly?: boolean;\n /** If true, the agent may execute this action concurrently with other\n * read-only or parallel-safe tool calls emitted in the same model turn.\n * Only set this for mutating actions that are internally concurrency-safe\n * and order-independent for same-turn execution. */\n parallelSafe?: boolean;\n /** Whether this action may be invoked from the tools (Alpine iframe) bridge\n * via `appAction(name, params)` — see `packages/core/docs/content/actions.md`\n * (\"Tools Callability\"). **Default-allow opt-out**: undefined / `true` both\n * allow tool-iframe calls; only an explicit `false` returns 403. Set to\n * `false` for high-blast-radius admin operations (account deletion, org\n * membership changes, anything that modifies auth state) — used by the\n * framework's `share-resource`, `unshare-resource`, and\n * `set-resource-visibility` for defense-in-depth. Regular UI/agent/CLI/MCP/A2A\n * calls are unaffected. Enforced by the action HTTP route layer — see\n * `packages/core/src/server/action-routes.ts`. Audit reference: H5 in\n * `security-audit/05-tools-sandbox.md`. */\n toolCallable?: boolean;\n /** Explicit public-agent exposure metadata. Public web routes never imply\n * public MCP/A2A/OpenAPI tool exposure. Actions must opt in here and public\n * protocol mounts must still filter for safe, route-appropriate tools. */\n publicAgent?: PublicAgentActionConfig;\n /** Optional deep-link builder. When set, MCP/A2A surfaces append an\n * \"Open in <app> →\" link built from the call's args + result so the\n * external agent can drop the user into the running app at the right\n * view/record. Pure + sync + best-effort. See the `external-agents` skill. */\n link?: ActionLinkBuilder;\n /** Optional MCP Apps UI resource for hosts that can render inline\n * interactive app iframes. Text/deep-link tool results remain the fallback\n * for CLI and non-UI hosts. */\n mcpApp?: ActionMcpAppConfig;\n}\n\n// ---------------------------------------------------------------------------\n// Legacy parameter-based action options\n// ---------------------------------------------------------------------------\n\ninterface DefineActionWithParams<\n TParams extends Record<string, ParameterSchema> | undefined =\n | Record<string, ParameterSchema>\n | undefined,\n TReturn = any,\n> {\n description: string;\n /** Flat map of parameter names to their schema. Automatically wrapped in\n * `{ type: \"object\", properties: ... }` for the Claude API. */\n parameters?: TParams;\n /** Standard Schema — not used in this overload. */\n schema?: never;\n run: (args: InferParams<TParams>) => Promise<TReturn> | TReturn;\n http?: ActionHttpConfig | false;\n /** If true, the framework will NOT emit a screen-refresh change event after a\n * successful call. Auto-inferred as `true` when `http.method === \"GET\"`. */\n readOnly?: boolean;\n /** If true, the agent may execute this action concurrently with other\n * read-only or parallel-safe tool calls emitted in the same model turn. */\n parallelSafe?: boolean;\n /** Whether this action may be invoked from the tools (Alpine iframe) bridge\n * via `appAction(name, params)`. See the schema overload above for details\n * and the `toolCallable` section in actions.md. */\n toolCallable?: boolean;\n /** Explicit public-agent exposure metadata. See schema overload above. */\n publicAgent?: PublicAgentActionConfig;\n /** Optional deep-link builder. See schema overload above. */\n link?: ActionLinkBuilder;\n /** Optional MCP Apps UI resource. See schema overload above. */\n mcpApp?: ActionMcpAppConfig;\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Define an agent action. Place in `actions/` directory — auto-discovered by the framework.\n *\n * Supports two modes:\n *\n * **Schema mode (recommended)** — pass a Standard Schema-compatible schema (Zod, Valibot,\n * ArkType) for runtime validation and full type inference:\n *\n * ```ts\n * import { defineAction } from \"@agent-native/core\";\n * import { z } from \"zod\";\n *\n * export default defineAction({\n * description: \"Create a form\",\n * schema: z.object({\n * title: z.string().describe(\"Form title\"),\n * status: z.enum([\"draft\", \"published\", \"closed\"]).default(\"draft\"),\n * }),\n * run: async (args) => {\n * // args is { title: string; status: \"draft\" | \"published\" | \"closed\" }\n * // Already validated — invalid inputs never reach here\n * },\n * });\n * ```\n *\n * **Parameters mode (legacy)** — pass raw JSON schema-like parameter definitions:\n *\n * ```ts\n * export default defineAction({\n * description: \"List events\",\n * parameters: {\n * from: { type: \"string\", description: \"Start date\" },\n * },\n * run: async (args) => { ... },\n * });\n * ```\n */\nexport function defineAction<TSchema extends StandardSchemaV1, TReturn>(\n options: DefineActionWithSchema<TSchema, TReturn>,\n): any;\nexport function defineAction<\n TParams extends Record<string, ParameterSchema> | undefined,\n TReturn,\n>(options: DefineActionWithParams<TParams, TReturn>): any;\nexport function defineAction(options: any) {\n const hasSchema = options.schema && \"~standard\" in options.schema;\n\n // Build tool definition for the Claude API\n let toolParameters: ActionTool[\"parameters\"];\n if (hasSchema) {\n // Convert Standard Schema to JSON Schema for Claude\n toolParameters = schemaToJsonSchema(options.schema, options.description);\n } else if (options.parameters) {\n toolParameters = {\n type: \"object\" as const,\n properties: options.parameters,\n };\n }\n\n // Wrap run() with validation when schema is provided.\n // Pass toolParameters so the validation error can echo the expected signature\n // (required vs optional fields) and help the caller self-correct.\n const run = hasSchema\n ? wrapWithValidation(options.schema, options.run, toolParameters)\n : options.run;\n\n // Auto-infer readOnly from http.method === \"GET\" unless explicitly set.\n // GET actions are idempotent reads; their completion should NOT trigger a\n // screen refresh. Everything else is assumed to mutate — the dispatcher\n // emits a change event on success so the UI auto-refetches its queries.\n const httpConfig = options.http as ActionHttpConfig | false | undefined;\n const inferredReadOnly =\n httpConfig !== false &&\n httpConfig !== undefined &&\n httpConfig.method === \"GET\";\n // Explicit `readOnly` (true OR false) wins. Otherwise infer from http.method.\n // We store the resolved boolean so downstream checks can trust entry.readOnly\n // without re-running method inference — including when a caller explicitly\n // passes readOnly:false to override a GET (rare but valid).\n const readOnly: boolean | undefined =\n typeof options.readOnly === \"boolean\"\n ? options.readOnly\n : inferredReadOnly\n ? true\n : undefined;\n\n // toolCallable: thread through whatever the caller declared. We DO NOT\n // default to `true` here — the absence of an explicit field is meaningful\n // to the tools bridge: it lets us emit a one-shot warning when an action\n // without a declared `toolCallable` flag is invoked from a tool, so the\n // ecosystem can migrate over time. The bridge treats `undefined` as\n // \"implicit allow with a deprecation warning\"; only an explicit `false`\n // refuses the call. See `extensions/routes.ts` and audit H5.\n const toolCallable: boolean | undefined =\n typeof options.toolCallable === \"boolean\"\n ? options.toolCallable\n : undefined;\n const parallelSafe: boolean | undefined =\n typeof options.parallelSafe === \"boolean\"\n ? options.parallelSafe\n : undefined;\n const publicAgent: PublicAgentActionConfig | undefined =\n options.publicAgent &&\n typeof options.publicAgent === \"object\" &&\n !Array.isArray(options.publicAgent)\n ? options.publicAgent\n : undefined;\n const link: ActionLinkBuilder | undefined =\n typeof options.link === \"function\" ? options.link : undefined;\n const mcpApp: ActionMcpAppConfig | undefined =\n options.mcpApp &&\n typeof options.mcpApp === \"object\" &&\n !Array.isArray(options.mcpApp) &&\n options.mcpApp.resource &&\n typeof options.mcpApp.resource === \"object\" &&\n !Array.isArray(options.mcpApp.resource) &&\n (typeof options.mcpApp.resource.html === \"string\" ||\n typeof options.mcpApp.resource.html === \"function\")\n ? options.mcpApp\n : undefined;\n\n return {\n tool: {\n description: options.description,\n parameters: toolParameters,\n },\n run,\n ...(hasSchema ? { schema: options.schema } : {}),\n ...(options.http !== undefined ? { http: options.http } : {}),\n ...(typeof readOnly === \"boolean\" ? { readOnly } : {}),\n ...(typeof parallelSafe === \"boolean\" ? { parallelSafe } : {}),\n ...(typeof toolCallable === \"boolean\" ? { toolCallable } : {}),\n ...(publicAgent ? { publicAgent } : {}),\n ...(link ? { link } : {}),\n ...(mcpApp ? { mcpApp } : {}),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Schema → JSON Schema conversion\n// ---------------------------------------------------------------------------\n\n/**\n * Convert a Standard Schema to JSON Schema for the Claude API.\n * Tries vendor-specific toJSONSchema first (Zod v4), then falls back\n * to a basic introspection of the schema shape.\n */\nfunction schemaToJsonSchema(\n schema: StandardSchemaV1,\n _description?: string,\n): ActionTool[\"parameters\"] {\n const s = schema as any;\n\n // Prefer Zod's own JSON Schema output — it handles descriptions,\n // enums, coerce, and all type wrappers correctly.\n if (s[\"~standard\"]?.jsonSchema?.input) {\n try {\n const result = s[\"~standard\"].jsonSchema.input({\n target: \"draft-07\",\n }) as any;\n // Strip $schema — the Claude API validates against draft 2020-12\n // and a mismatched $schema declaration can cause rejections.\n if (result && typeof result === \"object\") {\n delete result.$schema;\n }\n return result as ActionTool[\"parameters\"];\n } catch {\n // Fall through to manual converter\n }\n }\n\n // Fallback: manual conversion from Zod v4 internal defs\n if (s._zod?.def) {\n return zodDefToJsonSchema(s._zod.def);\n }\n\n // Last resort: empty object schema\n return { type: \"object\" as const, properties: {} };\n}\n\n/**\n * Convert a Zod v4 internal def to JSON Schema.\n * Handles the common types used in action parameters.\n */\nfunction zodDefToJsonSchema(def: any): any {\n const type = def.type;\n\n if (type === \"object\") {\n const properties: Record<string, any> = {};\n const required: string[] = [];\n const shape = def.shape;\n if (shape) {\n for (const [key, fieldSchema] of Object.entries(shape) as any[]) {\n const fieldDef = fieldSchema?._zod?.def;\n if (fieldDef) {\n const prop = zodDefToJsonSchema(fieldDef);\n // Zod v4 stores .describe() on the schema object, not in the def\n const desc = fieldSchema?.description;\n if (desc && !prop.description) prop.description = desc;\n properties[key] = prop;\n if (fieldDef.type !== \"optional\" && fieldDef.type !== \"default\") {\n required.push(key);\n }\n }\n }\n }\n const result: any = { type: \"object\", properties };\n if (required.length > 0) result.required = required;\n return result;\n }\n\n if (type === \"string\") {\n const result: any = { type: \"string\" };\n if (def.description) result.description = def.description;\n return result;\n }\n\n if (type === \"number\" || type === \"float\" || type === \"int\") {\n const result: any = { type: type === \"int\" ? \"integer\" : \"number\" };\n if (def.description) result.description = def.description;\n return result;\n }\n\n if (type === \"boolean\") {\n const result: any = { type: \"boolean\" };\n if (def.description) result.description = def.description;\n return result;\n }\n\n if (type === \"enum\") {\n // Zod v4 stores enum entries as an object {a: \"a\", b: \"b\"};\n // JSON Schema requires an array.\n const entries = def.entries;\n const enumValues = Array.isArray(entries)\n ? entries\n : typeof entries === \"object\" && entries !== null\n ? Object.values(entries)\n : entries;\n const result: any = { type: \"string\", enum: enumValues };\n if (def.description) result.description = def.description;\n return result;\n }\n\n if (type === \"literal\") {\n return { type: typeof def.value, enum: [def.value] };\n }\n\n if (type === \"array\") {\n const result: any = { type: \"array\" };\n if (def.element?._zod?.def) {\n result.items = zodDefToJsonSchema(def.element._zod.def);\n }\n if (def.description) result.description = def.description;\n return result;\n }\n\n if (type === \"optional\") {\n if (def.innerType?._zod?.def) {\n return zodDefToJsonSchema(def.innerType._zod.def);\n }\n }\n\n if (type === \"default\") {\n if (def.innerType?._zod?.def) {\n const inner = zodDefToJsonSchema(def.innerType._zod.def);\n inner.default =\n typeof def.defaultValue === \"function\"\n ? def.defaultValue()\n : def.defaultValue;\n return inner;\n }\n }\n\n if (type === \"nullable\") {\n if (def.innerType?._zod?.def) {\n return zodDefToJsonSchema(def.innerType._zod.def);\n }\n }\n\n if (type === \"union\") {\n if (def.options?.length) {\n // Check if it's a simple enum-like union of literals\n const allLiterals = def.options.every(\n (o: any) => o?._zod?.def?.type === \"literal\",\n );\n if (allLiterals) {\n return {\n type: \"string\",\n enum: def.options.map((o: any) => o._zod.def.value),\n };\n }\n return {\n anyOf: def.options.map((o: any) =>\n zodDefToJsonSchema(o._zod?.def ?? {}),\n ),\n };\n }\n }\n\n // Fallback\n return { type: \"string\" };\n}\n\n// ---------------------------------------------------------------------------\n// Runtime validation wrapper\n// ---------------------------------------------------------------------------\n\n/**\n * Wrap an action's run function with schema validation.\n * Invalid inputs get a clear error message (including what was actually passed)\n * so the agent can see its own mistake and correct it on the next turn.\n */\nfunction wrapWithValidation(\n schema: StandardSchemaV1,\n run: Function,\n toolParameters?: ActionTool[\"parameters\"],\n): (args: any) => any {\n return async (args: any) => {\n const result = await schema[\"~standard\"].validate(args);\n if (result.issues) {\n // Split issues into \"missing required field\" vs other validation errors\n // so the error message reads naturally rather than as \"fieldName: Required\".\n const missing: string[] = [];\n const other: string[] = [];\n for (const issue of result.issues) {\n const pathStr = issue.path\n ? issue.path.map((p) => (typeof p === \"object\" ? p.key : p)).join(\".\")\n : \"\";\n const msg = String(issue.message ?? \"\");\n // Zod emits \"Required\" for missing fields; other libraries may use\n // similar wording. Treat any variant as \"missing\".\n if (\n pathStr &&\n (msg === \"Required\" ||\n /invalid.*undefined/i.test(msg) ||\n /expected.*received undefined/i.test(msg))\n ) {\n missing.push(pathStr);\n } else {\n other.push(pathStr ? `${pathStr}: ${msg}` : msg);\n }\n }\n\n const parts: string[] = [];\n if (missing.length > 0) {\n parts.push(\n `Missing required parameter${missing.length === 1 ? \"\" : \"s\"}: ${missing.join(\", \")}`,\n );\n }\n if (other.length > 0) {\n parts.push(other.join(\"; \"));\n }\n\n // Echo the args that were actually passed so the caller (usually an\n // agent) can see exactly what it sent and fix its next call.\n let received: string;\n try {\n received = JSON.stringify(args);\n if (received.length > 500) received = received.slice(0, 500) + \"…\";\n } catch {\n received = String(args);\n }\n\n // Also show the EXPECTED signature so the agent doesn't have to guess.\n // Format: `{ deckId*: string, content*: string, slideId?: string, ... }`\n // where `*` = required, `?` = optional.\n let expected = \"\";\n if (toolParameters?.properties) {\n const required = new Set(toolParameters.required ?? []);\n const sig = Object.entries(toolParameters.properties)\n .map(([k, v]) => {\n const mark = required.has(k) ? \"*\" : \"?\";\n const type = (v as { type?: string }).type ?? \"any\";\n return `${k}${mark}: ${type}`;\n })\n .join(\", \");\n if (sig)\n expected = ` Expected: { ${sig} } (where * = required, ? = optional).`;\n }\n\n throw new Error(\n `Invalid action parameters — ${parts.join(\". \")}. Received: ${received}.${expected}`,\n );\n }\n return run((result as StandardSchemaV1.SuccessResult<any>).value);\n };\n}\n"]}
1
+ {"version":3,"file":"action.js","sourceRoot":"","sources":["../src/action.ts"],"names":[],"mappings":"AAUA;;;GAGG;AACH,MAAM,OAAO,oBAAqB,SAAQ,KAAK;IACpC,eAAe,GAAG,IAAI,CAAC;IACvB,SAAS,CAAU;IACnB,UAAU,CAAU;IAE7B,YAAY,OAAe,EAAE,UAAkC,EAAE;QAC/D,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,sBAAsB,CAAC;QACnC,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,SAAS,CAAC;QACnC,IAAI,CAAC,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC;IACvC,CAAC;CACF;AAED,MAAM,UAAU,sBAAsB,CACpC,GAAY;IAEZ,OAAO,CACL,GAAG,YAAY,oBAAoB;QACnC,OAAO,CACL,GAAG;YACH,OAAO,GAAG,KAAK,QAAQ;YACvB,iBAAiB,IAAI,GAAG;YACvB,GAAqC,CAAC,eAAe,KAAK,IAAI,CAChE,CACF,CAAC;AACJ,CAAC;AA0CD,MAAM,CAAC,MAAM,oBAAoB,GAAG,4BAAqC,CAAC;AAC1E,MAAM,CAAC,MAAM,iBAAiB,GAAG,2BAAoC,CAAC;AACtE,MAAM,CAAC,MAAM,6BAA6B,GAAG,gBAAyB,CAAC;AAkOvE,MAAM,UAAU,YAAY,CAAC,OAAY;IACvC,MAAM,SAAS,GAAG,OAAO,CAAC,MAAM,IAAI,WAAW,IAAI,OAAO,CAAC,MAAM,CAAC;IAElE,2CAA2C;IAC3C,IAAI,cAAwC,CAAC;IAC7C,IAAI,SAAS,EAAE,CAAC;QACd,oDAAoD;QACpD,cAAc,GAAG,kBAAkB,CAAC,O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AAC;oBACzC,MAAM,IAAI,GAAI,CAAuB,CAAC,IAAI,IAAI,KAAK,CAAC;oBACpD,OAAO,GAAG,CAAC,GAAG,IAAI,KAAK,IAAI,EAAE,CAAC;gBAChC,CAAC,CAAC;qBACD,IAAI,CAAC,IAAI,CAAC,CAAC;gBACd,IAAI,GAAG;oBACL,QAAQ,GAAG,gBAAgB,GAAG,wCAAwC,CAAC;YAC3E,CAAC;YAED,MAAM,IAAI,KAAK,CACb,+BAA+B,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,eAAe,QAAQ,IAAI,QAAQ,EAAE,CACrF,CAAC;QACJ,CAAC;QACD,OAAO,GAAG,CAAE,MAA8C,CAAC,KAAK,CAAC,CAAC;IACpE,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import type { ActionTool } from \"./agent/types.js\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\n\nexport interface AgentActionStopOptions {\n /** Optional stable code surfaced in run metadata and tests. */\n errorCode?: string;\n /** Optional short tool-result text. Defaults to the user-facing message. */\n toolResult?: string;\n}\n\n/**\n * Throw from an action when the agent should stop the current turn instead of\n * feeding the failure back to the model for another retry.\n */\nexport class AgentActionStopError extends Error {\n readonly agentNativeStop = true;\n readonly errorCode?: string;\n readonly toolResult?: string;\n\n constructor(message: string, options: AgentActionStopOptions = {}) {\n super(message);\n this.name = \"AgentActionStopError\";\n this.errorCode = options.errorCode;\n this.toolResult = options.toolResult;\n }\n}\n\nexport function isAgentActionStopError(\n err: unknown,\n): err is AgentActionStopError {\n return (\n err instanceof AgentActionStopError ||\n Boolean(\n err &&\n typeof err === \"object\" &&\n \"agentNativeStop\" in err &&\n (err as { agentNativeStop?: unknown }).agentNativeStop === true,\n )\n );\n}\n\n/** HTTP exposure config for an action. */\nexport interface ActionHttpConfig {\n /** HTTP method. Default: \"POST\". Use \"GET\" for read-only actions. */\n method?: \"GET\" | \"POST\" | \"PUT\" | \"DELETE\";\n /** Override route path under /_agent-native/actions/. Default: action filename. */\n path?: string;\n}\n\n/** Explicit opt-in metadata for public agent protocols such as MCP or A2A. */\nexport interface PublicAgentActionConfig {\n expose: boolean;\n readOnly: boolean;\n requiresAuth?: boolean;\n isConsequential?: boolean;\n title?: string;\n description?: string;\n}\n\n/** A deep link an external agent (MCP / A2A) can surface to the user so they\n * can open the produced/listed resource in the running app UI. */\nexport interface ActionDeepLink {\n /** App-relative path (e.g. `/_agent-native/open?app=mail&view=inbox&...`)\n * or an absolute URL. The MCP layer prefixes the request origin when this\n * is relative, and may rewrite it to the `agentnative://` desktop scheme. */\n url: string;\n /** Human-readable label, e.g. \"Open draft in Mail\". */\n label: string;\n /** Optional view hint (matches the `navigate` command `view`). */\n view?: string;\n}\n\n/** Builds a deep link from an action's args + result so external agents can\n * surface an \"Open in <app> →\" link. MUST be pure and synchronous — no I/O,\n * no awaits. Best-effort: a throw or null is swallowed and never fails the\n * tool call. See the `external-agents` skill. */\nexport type ActionLinkBuilder = (ctx: {\n args: Record<string, any>;\n result: any;\n}) => ActionDeepLink | null | undefined;\n\nexport const MCP_APP_EXTENSION_ID = \"io.modelcontextprotocol/ui\" as const;\nexport const MCP_APP_MIME_TYPE = \"text/html;profile=mcp-app\" as const;\nexport const MCP_APP_RESOURCE_URI_META_KEY = \"ui/resourceUri\" as const;\n\nexport interface ActionMcpAppCsp {\n connectDomains?: string[];\n resourceDomains?: string[];\n frameDomains?: string[];\n baseUriDomains?: string[];\n}\n\nexport type ActionMcpAppCspBuilder = (ctx: {\n actionName: string;\n appId?: string;\n requestOrigin?: string;\n}) => ActionMcpAppCsp | Promise<ActionMcpAppCsp>;\n\nexport interface ActionMcpAppPermissions {\n camera?: Record<string, never>;\n microphone?: Record<string, never>;\n geolocation?: Record<string, never>;\n clipboardWrite?: Record<string, never>;\n}\n\nexport interface ActionMcpAppResourceMeta {\n csp?: ActionMcpAppCsp | ActionMcpAppCspBuilder;\n permissions?: ActionMcpAppPermissions;\n domain?: string;\n prefersBorder?: boolean;\n}\n\nexport type ActionMcpAppHtmlBuilder = (ctx: {\n actionName: string;\n appId?: string;\n requestOrigin?: string;\n}) => string;\n\nexport interface ActionMcpAppResourceConfig {\n /** `ui://` URI. Defaults to `ui://<app>/<action-name>`. */\n uri?: string;\n /** MCP resource name. Defaults to the action name. */\n name?: string;\n title?: string;\n description?: string;\n /**\n * HTML5 document content for the MCP App resource. Keep this self-contained\n * or declare any external origins in `csp`.\n */\n html: string | ActionMcpAppHtmlBuilder;\n /** Defaults to the MCP Apps HTML MIME type. */\n mimeType?: typeof MCP_APP_MIME_TYPE;\n /** Extra resource/content metadata. `ui` is merged with the fields below. */\n _meta?: Record<string, unknown>;\n csp?: ActionMcpAppCsp | ActionMcpAppCspBuilder;\n permissions?: ActionMcpAppPermissions;\n domain?: string;\n prefersBorder?: boolean;\n}\n\nexport interface ActionMcpAppConfig {\n resource: ActionMcpAppResourceConfig;\n /**\n * MCP Apps tool visibility. Defaults to model + app so the LLM can call the\n * action and the app iframe can call it back through the host bridge.\n */\n visibility?: Array<\"model\" | \"app\">;\n /**\n * Rare escape hatch for MCP Apps chat hosts. By default OAuth callers with\n * `mcp:apps` see the generic app tools (`open_app`, `list_apps`, etc.) so\n * hosts do not ingest every action-specific UI resource. Set this only when\n * this specific action must stay visible in that compact catalog.\n */\n compactCatalog?: boolean;\n}\n\n/** Schema definition for a single action parameter (legacy JSON schema style). */\nexport interface ParameterSchema {\n type: string;\n description?: string;\n enum?: string[];\n}\n\n/** Infer runtime parameter types from a legacy parameter schema map. */\ntype InferParams<T extends Record<string, ParameterSchema> | undefined> =\n T extends Record<string, ParameterSchema>\n ? { [K in keyof T]?: string }\n : Record<string, string>;\n\n// ---------------------------------------------------------------------------\n// Schema-based action options (new: Zod / Valibot / ArkType via Standard Schema)\n// ---------------------------------------------------------------------------\n\ninterface DefineActionWithSchema<\n TSchema extends StandardSchemaV1,\n TReturn = any,\n> {\n description: string;\n /** Standard Schema-compatible schema (Zod, Valibot, ArkType). Provides runtime\n * validation and full TypeScript type inference for `run()` args. The schema is\n * also converted to JSON Schema for the Claude API tool definition. */\n schema: TSchema;\n /** Legacy parameters — ignored when `schema` is provided. */\n parameters?: never;\n run: (\n args: StandardSchemaV1.InferOutput<TSchema>,\n ) => Promise<TReturn> | TReturn;\n http?: ActionHttpConfig | false;\n /** If true, the framework will NOT emit a screen-refresh change event after a\n * successful call. Auto-inferred as `true` when `http.method === \"GET\"`.\n * Only set this manually when you need to override the inference — e.g. a\n * POST action that only reads data but can't use GET for a protocol reason. */\n readOnly?: boolean;\n /** If true, the agent may execute this action concurrently with other\n * read-only or parallel-safe tool calls emitted in the same model turn.\n * Only set this for mutating actions that are internally concurrency-safe\n * and order-independent for same-turn execution. */\n parallelSafe?: boolean;\n /** Whether this action may be invoked from the tools (Alpine iframe) bridge\n * via `appAction(name, params)` — see `packages/core/docs/content/actions.md`\n * (\"Tools Callability\"). **Default-allow opt-out**: undefined / `true` both\n * allow tool-iframe calls; only an explicit `false` returns 403. Set to\n * `false` for high-blast-radius admin operations (account deletion, org\n * membership changes, anything that modifies auth state) — used by the\n * framework's `share-resource`, `unshare-resource`, and\n * `set-resource-visibility` for defense-in-depth. Regular UI/agent/CLI/MCP/A2A\n * calls are unaffected. Enforced by the action HTTP route layer — see\n * `packages/core/src/server/action-routes.ts`. Audit reference: H5 in\n * `security-audit/05-tools-sandbox.md`. */\n toolCallable?: boolean;\n /** Explicit public-agent exposure metadata. Public web routes never imply\n * public MCP/A2A/OpenAPI tool exposure. Actions must opt in here and public\n * protocol mounts must still filter for safe, route-appropriate tools. */\n publicAgent?: PublicAgentActionConfig;\n /** Optional deep-link builder. When set, MCP/A2A surfaces append an\n * \"Open in <app> →\" link built from the call's args + result so the\n * external agent can drop the user into the running app at the right\n * view/record. Pure + sync + best-effort. See the `external-agents` skill. */\n link?: ActionLinkBuilder;\n /** Optional MCP Apps UI resource for hosts that can render inline\n * interactive app iframes. Text/deep-link tool results remain the fallback\n * for CLI and non-UI hosts. */\n mcpApp?: ActionMcpAppConfig;\n}\n\n// ---------------------------------------------------------------------------\n// Legacy parameter-based action options\n// ---------------------------------------------------------------------------\n\ninterface DefineActionWithParams<\n TParams extends Record<string, ParameterSchema> | undefined =\n | Record<string, ParameterSchema>\n | undefined,\n TReturn = any,\n> {\n description: string;\n /** Flat map of parameter names to their schema. Automatically wrapped in\n * `{ type: \"object\", properties: ... }` for the Claude API. */\n parameters?: TParams;\n /** Standard Schema — not used in this overload. */\n schema?: never;\n run: (args: InferParams<TParams>) => Promise<TReturn> | TReturn;\n http?: ActionHttpConfig | false;\n /** If true, the framework will NOT emit a screen-refresh change event after a\n * successful call. Auto-inferred as `true` when `http.method === \"GET\"`. */\n readOnly?: boolean;\n /** If true, the agent may execute this action concurrently with other\n * read-only or parallel-safe tool calls emitted in the same model turn. */\n parallelSafe?: boolean;\n /** Whether this action may be invoked from the tools (Alpine iframe) bridge\n * via `appAction(name, params)`. See the schema overload above for details\n * and the `toolCallable` section in actions.md. */\n toolCallable?: boolean;\n /** Explicit public-agent exposure metadata. See schema overload above. */\n publicAgent?: PublicAgentActionConfig;\n /** Optional deep-link builder. See schema overload above. */\n link?: ActionLinkBuilder;\n /** Optional MCP Apps UI resource. See schema overload above. */\n mcpApp?: ActionMcpAppConfig;\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Define an agent action. Place in `actions/` directory — auto-discovered by the framework.\n *\n * Supports two modes:\n *\n * **Schema mode (recommended)** — pass a Standard Schema-compatible schema (Zod, Valibot,\n * ArkType) for runtime validation and full type inference:\n *\n * ```ts\n * import { defineAction } from \"@agent-native/core\";\n * import { z } from \"zod\";\n *\n * export default defineAction({\n * description: \"Create a form\",\n * schema: z.object({\n * title: z.string().describe(\"Form title\"),\n * status: z.enum([\"draft\", \"published\", \"closed\"]).default(\"draft\"),\n * }),\n * run: async (args) => {\n * // args is { title: string; status: \"draft\" | \"published\" | \"closed\" }\n * // Already validated — invalid inputs never reach here\n * },\n * });\n * ```\n *\n * **Parameters mode (legacy)** — pass raw JSON schema-like parameter definitions:\n *\n * ```ts\n * export default defineAction({\n * description: \"List events\",\n * parameters: {\n * from: { type: \"string\", description: \"Start date\" },\n * },\n * run: async (args) => { ... },\n * });\n * ```\n */\nexport function defineAction<TSchema extends StandardSchemaV1, TReturn>(\n options: DefineActionWithSchema<TSchema, TReturn>,\n): any;\nexport function defineAction<\n TParams extends Record<string, ParameterSchema> | undefined,\n TReturn,\n>(options: DefineActionWithParams<TParams, TReturn>): any;\nexport function defineAction(options: any) {\n const hasSchema = options.schema && \"~standard\" in options.schema;\n\n // Build tool definition for the Claude API\n let toolParameters: ActionTool[\"parameters\"];\n if (hasSchema) {\n // Convert Standard Schema to JSON Schema for Claude\n toolParameters = schemaToJsonSchema(options.schema, options.description);\n } else if (options.parameters) {\n toolParameters = {\n type: \"object\" as const,\n properties: options.parameters,\n };\n }\n\n // Wrap run() with validation when schema is provided.\n // Pass toolParameters so the validation error can echo the expected signature\n // (required vs optional fields) and help the caller self-correct.\n const run = hasSchema\n ? wrapWithValidation(options.schema, options.run, toolParameters)\n : options.run;\n\n // Auto-infer readOnly from http.method === \"GET\" unless explicitly set.\n // GET actions are idempotent reads; their completion should NOT trigger a\n // screen refresh. Everything else is assumed to mutate — the dispatcher\n // emits a change event on success so the UI auto-refetches its queries.\n const httpConfig = options.http as ActionHttpConfig | false | undefined;\n const inferredReadOnly =\n httpConfig !== false &&\n httpConfig !== undefined &&\n httpConfig.method === \"GET\";\n // Explicit `readOnly` (true OR false) wins. Otherwise infer from http.method.\n // We store the resolved boolean so downstream checks can trust entry.readOnly\n // without re-running method inference — including when a caller explicitly\n // passes readOnly:false to override a GET (rare but valid).\n const readOnly: boolean | undefined =\n typeof options.readOnly === \"boolean\"\n ? options.readOnly\n : inferredReadOnly\n ? true\n : undefined;\n\n // toolCallable: thread through whatever the caller declared. We DO NOT\n // default to `true` here — the absence of an explicit field is meaningful\n // to the tools bridge: it lets us emit a one-shot warning when an action\n // without a declared `toolCallable` flag is invoked from a tool, so the\n // ecosystem can migrate over time. The bridge treats `undefined` as\n // \"implicit allow with a deprecation warning\"; only an explicit `false`\n // refuses the call. See `extensions/routes.ts` and audit H5.\n const toolCallable: boolean | undefined =\n typeof options.toolCallable === \"boolean\"\n ? options.toolCallable\n : undefined;\n const parallelSafe: boolean | undefined =\n typeof options.parallelSafe === \"boolean\"\n ? options.parallelSafe\n : undefined;\n const publicAgent: PublicAgentActionConfig | undefined =\n options.publicAgent &&\n typeof options.publicAgent === \"object\" &&\n !Array.isArray(options.publicAgent)\n ? options.publicAgent\n : undefined;\n const link: ActionLinkBuilder | undefined =\n typeof options.link === \"function\" ? options.link : undefined;\n const mcpApp: ActionMcpAppConfig | undefined =\n options.mcpApp &&\n typeof options.mcpApp === \"object\" &&\n !Array.isArray(options.mcpApp) &&\n options.mcpApp.resource &&\n typeof options.mcpApp.resource === \"object\" &&\n !Array.isArray(options.mcpApp.resource) &&\n (typeof options.mcpApp.resource.html === \"string\" ||\n typeof options.mcpApp.resource.html === \"function\")\n ? options.mcpApp\n : undefined;\n\n return {\n tool: {\n description: options.description,\n parameters: toolParameters,\n },\n run,\n ...(hasSchema ? { schema: options.schema } : {}),\n ...(options.http !== undefined ? { http: options.http } : {}),\n ...(typeof readOnly === \"boolean\" ? { readOnly } : {}),\n ...(typeof parallelSafe === \"boolean\" ? { parallelSafe } : {}),\n ...(typeof toolCallable === \"boolean\" ? { toolCallable } : {}),\n ...(publicAgent ? { publicAgent } : {}),\n ...(link ? { link } : {}),\n ...(mcpApp ? { mcpApp } : {}),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Schema → JSON Schema conversion\n// ---------------------------------------------------------------------------\n\n/**\n * Convert a Standard Schema to JSON Schema for the Claude API.\n * Tries vendor-specific toJSONSchema first (Zod v4), then falls back\n * to a basic introspection of the schema shape.\n */\nfunction schemaToJsonSchema(\n schema: StandardSchemaV1,\n _description?: string,\n): ActionTool[\"parameters\"] {\n const s = schema as any;\n\n // Prefer Zod's own JSON Schema output — it handles descriptions,\n // enums, coerce, and all type wrappers correctly.\n if (s[\"~standard\"]?.jsonSchema?.input) {\n try {\n const result = s[\"~standard\"].jsonSchema.input({\n target: \"draft-07\",\n }) as any;\n // Strip $schema — the Claude API validates against draft 2020-12\n // and a mismatched $schema declaration can cause rejections.\n if (result && typeof result === \"object\") {\n delete result.$schema;\n }\n return result as ActionTool[\"parameters\"];\n } catch {\n // Fall through to manual converter\n }\n }\n\n // Fallback: manual conversion from Zod v4 internal defs\n if (s._zod?.def) {\n return zodDefToJsonSchema(s._zod.def);\n }\n\n // Last resort: empty object schema\n return { type: \"object\" as const, properties: {} };\n}\n\n/**\n * Convert a Zod v4 internal def to JSON Schema.\n * Handles the common types used in action parameters.\n */\nfunction zodDefToJsonSchema(def: any): any {\n const type = def.type;\n\n if (type === \"object\") {\n const properties: Record<string, any> = {};\n const required: string[] = [];\n const shape = def.shape;\n if (shape) {\n for (const [key, fieldSchema] of Object.entries(shape) as any[]) {\n const fieldDef = fieldSchema?._zod?.def;\n if (fieldDef) {\n const prop = zodDefToJsonSchema(fieldDef);\n // Zod v4 stores .describe() on the schema object, not in the def\n const desc = fieldSchema?.description;\n if (desc && !prop.description) prop.description = desc;\n properties[key] = prop;\n if (fieldDef.type !== \"optional\" && fieldDef.type !== \"default\") {\n required.push(key);\n }\n }\n }\n }\n const result: any = { type: \"object\", properties };\n if (required.length > 0) result.required = required;\n return result;\n }\n\n if (type === \"string\") {\n const result: any = { type: \"string\" };\n if (def.description) result.description = def.description;\n return result;\n }\n\n if (type === \"number\" || type === \"float\" || type === \"int\") {\n const result: any = { type: type === \"int\" ? \"integer\" : \"number\" };\n if (def.description) result.description = def.description;\n return result;\n }\n\n if (type === \"boolean\") {\n const result: any = { type: \"boolean\" };\n if (def.description) result.description = def.description;\n return result;\n }\n\n if (type === \"enum\") {\n // Zod v4 stores enum entries as an object {a: \"a\", b: \"b\"};\n // JSON Schema requires an array.\n const entries = def.entries;\n const enumValues = Array.isArray(entries)\n ? entries\n : typeof entries === \"object\" && entries !== null\n ? Object.values(entries)\n : entries;\n const result: any = { type: \"string\", enum: enumValues };\n if (def.description) result.description = def.description;\n return result;\n }\n\n if (type === \"literal\") {\n return { type: typeof def.value, enum: [def.value] };\n }\n\n if (type === \"array\") {\n const result: any = { type: \"array\" };\n if (def.element?._zod?.def) {\n result.items = zodDefToJsonSchema(def.element._zod.def);\n }\n if (def.description) result.description = def.description;\n return result;\n }\n\n if (type === \"optional\") {\n if (def.innerType?._zod?.def) {\n return zodDefToJsonSchema(def.innerType._zod.def);\n }\n }\n\n if (type === \"default\") {\n if (def.innerType?._zod?.def) {\n const inner = zodDefToJsonSchema(def.innerType._zod.def);\n inner.default =\n typeof def.defaultValue === \"function\"\n ? def.defaultValue()\n : def.defaultValue;\n return inner;\n }\n }\n\n if (type === \"nullable\") {\n if (def.innerType?._zod?.def) {\n return zodDefToJsonSchema(def.innerType._zod.def);\n }\n }\n\n if (type === \"union\") {\n if (def.options?.length) {\n // Check if it's a simple enum-like union of literals\n const allLiterals = def.options.every(\n (o: any) => o?._zod?.def?.type === \"literal\",\n );\n if (allLiterals) {\n return {\n type: \"string\",\n enum: def.options.map((o: any) => o._zod.def.value),\n };\n }\n return {\n anyOf: def.options.map((o: any) =>\n zodDefToJsonSchema(o._zod?.def ?? {}),\n ),\n };\n }\n }\n\n // Fallback\n return { type: \"string\" };\n}\n\n// ---------------------------------------------------------------------------\n// Runtime validation wrapper\n// ---------------------------------------------------------------------------\n\n/**\n * Wrap an action's run function with schema validation.\n * Invalid inputs get a clear error message (including what was actually passed)\n * so the agent can see its own mistake and correct it on the next turn.\n */\nfunction wrapWithValidation(\n schema: StandardSchemaV1,\n run: Function,\n toolParameters?: ActionTool[\"parameters\"],\n): (args: any) => any {\n return async (args: any) => {\n const result = await schema[\"~standard\"].validate(args);\n if (result.issues) {\n // Split issues into \"missing required field\" vs other validation errors\n // so the error message reads naturally rather than as \"fieldName: Required\".\n const missing: string[] = [];\n const other: string[] = [];\n for (const issue of result.issues) {\n const pathStr = issue.path\n ? issue.path.map((p) => (typeof p === \"object\" ? p.key : p)).join(\".\")\n : \"\";\n const msg = String(issue.message ?? \"\");\n // Zod emits \"Required\" for missing fields; other libraries may use\n // similar wording. Treat any variant as \"missing\".\n if (\n pathStr &&\n (msg === \"Required\" ||\n /invalid.*undefined/i.test(msg) ||\n /expected.*received undefined/i.test(msg))\n ) {\n missing.push(pathStr);\n } else {\n other.push(pathStr ? `${pathStr}: ${msg}` : msg);\n }\n }\n\n const parts: string[] = [];\n if (missing.length > 0) {\n parts.push(\n `Missing required parameter${missing.length === 1 ? \"\" : \"s\"}: ${missing.join(\", \")}`,\n );\n }\n if (other.length > 0) {\n parts.push(other.join(\"; \"));\n }\n\n // Echo the args that were actually passed so the caller (usually an\n // agent) can see exactly what it sent and fix its next call.\n let received: string;\n try {\n received = JSON.stringify(args);\n if (received.length > 500) received = received.slice(0, 500) + \"…\";\n } catch {\n received = String(args);\n }\n\n // Also show the EXPECTED signature so the agent doesn't have to guess.\n // Format: `{ deckId*: string, content*: string, slideId?: string, ... }`\n // where `*` = required, `?` = optional.\n let expected = \"\";\n if (toolParameters?.properties) {\n const required = new Set(toolParameters.required ?? []);\n const sig = Object.entries(toolParameters.properties)\n .map(([k, v]) => {\n const mark = required.has(k) ? \"*\" : \"?\";\n const type = (v as { type?: string }).type ?? \"any\";\n return `${k}${mark}: ${type}`;\n })\n .join(\", \");\n if (sig)\n expected = ` Expected: { ${sig} } (where * = required, ? = optional).`;\n }\n\n throw new Error(\n `Invalid action parameters — ${parts.join(\". \")}. Received: ${received}.${expected}`,\n );\n }\n return run((result as StandardSchemaV1.SuccessResult<any>).value);\n };\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"build-server.d.ts","sourceRoot":"","sources":["../../src/mcp/build-server.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAA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,CAC7C,MAAM,EAAE,SAAS,EACjB,QAAQ,EAAE,iBAAiB,GAAG,SAAS,EACvC,WAAW,CAAC,EAAE,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IA2Z7B;AAOD,wBAAgB,eAAe,IAAI,MAAM,EAAE,CAc1C;AA+FD;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAsB,UAAU,CAC9B,UAAU,EAAE,MAAM,GAAG,SAAS,EAC9B,gBAAgB,CAAC,EAAE,MAAM,GAAG,SAAS,EACrC,OAAO,GAAE;IAAE,YAAY,CAAC,EAAE,OAAO,CAAC;IAAC,WAAW,CAAC,EAAE,MAAM,CAAA;CAAO,GAC7D,OAAO,CAAC;IACT,MAAM,EAAE,OAAO,CAAC;IAChB,QAAQ,CAAC,EAAE,iBAAiB,CAAC;IAC7B;;;;;;OAMG;IACH,WAAW,CAAC,EAAE,OAAO,CAAC;CACvB,CAAC,CAoHD;AAED,wBAAsB,sBAAsB,CAC1C,SAAS,EAAE,MAAM,GAAG,SAAS,GAC5B,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAS7B"}
@@ -36,19 +36,24 @@ function isActionVisibleForOAuthScope(entry, scopes) {
36
36
  const COMPACT_MCP_APP_CATALOG_BUILTINS = new Set([
37
37
  "list_apps",
38
38
  "open_app",
39
+ "ask_app",
39
40
  "create_embed_session",
40
41
  ]);
41
- function isDispatchConfig(config) {
42
- const id = (config.appId ?? "").toLowerCase();
43
- const name = (config.name ?? "").toLowerCase();
44
- return id === "dispatch" || name.includes("dispatch");
45
- }
46
42
  function isActionAdvertisedInCompactMcpAppCatalog(config, name, entry) {
47
43
  if (COMPACT_MCP_APP_CATALOG_BUILTINS.has(name))
48
44
  return true;
49
- if (name === "ask_app" && isDispatchConfig(config))
45
+ if (entry.mcpApp
46
+ ?.compactCatalog === true) {
50
47
  return true;
51
- return Boolean(entry.mcpApp?.resource);
48
+ }
49
+ // If an app deliberately disables the generic open_app builtin, fall back to
50
+ // its action-specific MCP App tools so it still has a UI surface. The normal
51
+ // default is the opposite: keep chat-host catalogs tiny and route UI via
52
+ // open_app instead of listing every app action/template.
53
+ if (config.builtinCrossAppTools === false) {
54
+ return Boolean(entry.mcpApp?.resource);
55
+ }
56
+ return false;
52
57
  }
53
58
  const MCP_APP_OAUTH_CLIENT_RE = /\b(chatgpt|openai|claude|anthropic)\b/i;
54
59
  const NON_APP_OAUTH_CLIENT_RE = /\b(code|desktop|cli|cursor|codex|goose|postman|mcpjam|inspector)\b/i;
@@ -110,6 +115,16 @@ function metadataObject(value) {
110
115
  ? value
111
116
  : {};
112
117
  }
118
+ function originString(value) {
119
+ if (typeof value !== "string" || !value.trim())
120
+ return undefined;
121
+ try {
122
+ return new URL(value).origin;
123
+ }
124
+ catch {
125
+ return undefined;
126
+ }
127
+ }
113
128
  function withMcpChatBridgeParam(urlOrPath) {
114
129
  try {
115
130
  const base = "http://agent-native.invalid";
@@ -300,8 +315,11 @@ function mcpAppUiMeta(resource, resolvedCsp, requestMeta, description) {
300
315
  }
301
316
  if (resource.permissions)
302
317
  ui.permissions = resource.permissions;
303
- if (resource.domain)
304
- ui.domain = resource.domain;
318
+ const widgetDomain = originString(resource.domain) ??
319
+ originString(ui.domain) ??
320
+ originString(requestMeta?.origin);
321
+ if (widgetDomain)
322
+ ui.domain = widgetDomain;
305
323
  if (typeof resource.prefersBorder === "boolean") {
306
324
  ui.prefersBorder = resource.prefersBorder;
307
325
  }
@@ -318,6 +336,9 @@ function mcpAppUiMeta(resource, resolvedCsp, requestMeta, description) {
318
336
  if (openAiCsp && base["openai/widgetCSP"] == null) {
319
337
  base["openai/widgetCSP"] = openAiCsp;
320
338
  }
339
+ if (widgetDomain && base["openai/widgetDomain"] == null) {
340
+ base["openai/widgetDomain"] = widgetDomain;
341
+ }
321
342
  return Object.keys(base).length > 0 ? base : undefined;
322
343
  }
323
344
  async function resolveMcpAppCsp(resource, ctx) {
@@ -1 +1 @@
1
- {"version":3,"file":"build-server.js","source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AChD,OAAO,GAAG,EAAE,KAAK,IAAI,SAAS,CAAC;IACjC,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,SAAS,CAAC;IACnB,CAAC;AACH,CAAC","sourcesContent":["/**\n * Shared MCP server builder.\n *\n * Extracted from `server.ts` so the stateless Streamable-HTTP mount\n * (`mountMCP`) and the stdio transport (`runMCPStdio --standalone`) build the\n * *same* MCP server from the *same* `ActionEntry` registry. Both surfaces:\n *\n * - expose every action as an MCP tool (+ the `ask-agent` meta-tool),\n * - append the framework deep-link block / `_meta` to every tool result,\n * - wrap `run()` / `askAgent()` in `runWithRequestContext` so per-user /\n * per-org scoping (accessFilter, resolveCredential, MCP visibility) is\n * honoured.\n *\n * `server.ts` re-exports `createMCPServerForRequest` and the auth helpers so\n * any (future) external importer of `@agent-native/core/mcp` keeps resolving.\n *\n * Node-only at the SDK level, but this module itself has no Node-only imports\n * — it can be bundled into the serverless function alongside `mountMCP`.\n */\n\nimport type { ActionEntry } from \"../agent/production-agent.js\";\nimport { isMcpActionResult } from \"../mcp-client/app-result.js\";\nimport {\n MCP_APP_EXTENSION_ID,\n MCP_APP_MIME_TYPE,\n MCP_APP_RESOURCE_URI_META_KEY,\n type ActionMcpAppCsp,\n type ActionMcpAppResourceConfig,\n} from \"../action.js\";\nimport { MCP_APP_REQUEST_ORIGIN_CSP_SOURCE } from \"./embed-app.js\";\nimport { runWithRequestContext } from \"../server/request-context.js\";\nimport { toAbsoluteOpenUrl, toDesktopOpenUrl } from \"../server/deep-link.js\";\nimport {\n isAgentNativeOpenDeepLink,\n withCollapsedAgentSidebarParam,\n} from \"../shared/agent-sidebar-url.js\";\nimport { MCP_APP_CHAT_BRIDGE_QUERY_PARAM } from \"../shared/embed-auth.js\";\nimport { getBuiltinCrossAppTools } from \"./builtin-tools.js\";\nimport { MCP_CONNECT_SCOPE } from \"./connect-store.js\";\nimport {\n MCP_OAUTH_SCOPES,\n hasMcpOAuthScope,\n verifyMcpOAuthAccessToken,\n} from \"./oauth-token.js\";\n\nexport interface MCPConfig {\n /** App name shown in MCP server info */\n name: string;\n /**\n * Canonical app id (directory under `apps/`, e.g. `mail`) this MCP server\n * is mounted for. Optional & back-compat: when omitted the builtin\n * cross-app tools fall back to lowercasing `name`. Used by `open_app` /\n * `ask_app` / `create_workspace_app` to tell \"this app\" from a cross-app\n * target so they resolve the *target* app's origin rather than echoing the\n * current request origin.\n */\n appId?: string;\n /** App description */\n description: string;\n /** Version string (default \"1.0.0\") */\n version?: string;\n /** Action registry — same as agent chat and A2A */\n actions: Record<string, ActionEntry>;\n /**\n * Full (\"production\") action surface served to an **authenticated real\n * caller** — a connect-minted token, an `agent-native mcp install` stdio\n * proxy (owner-email header / `AGENT_NATIVE_OWNER_EMAIL`), or a deployed /\n * `AGENT_MODE=production` app. In local dev `actions` is intentionally the\n * sparse, dev-toggled surface (builtins + read-only public-agent actions)\n * so the local agent chat and unauthenticated dev probes don't see every\n * mutating tool; but per the external-agents contract a real caller that\n * connected with a token MUST get the full surface even in dev. When unset\n * (production, where `actions` already IS the full set) the swap is a\n * no-op. See `external-agents` skill, \"Dev vs production tool surface\".\n */\n productionActions?: Record<string, ActionEntry>;\n /** Handler for the ask-agent meta-tool — runs the full agent loop */\n askAgent?: (message: string) => Promise<string>;\n /**\n * Disable the generic cross-app builtin tools (`list_apps`, `open_app`,\n * `ask_app`, `create_workspace_app`, `list_templates`). They are merged in\n * by default so external agents get a stable verb set; a template action of\n * the same name always wins (template precedence). Set to `false` only for\n * a constrained / locked-down mount.\n */\n builtinCrossAppTools?: boolean;\n}\n\n/**\n * Identity extracted from a verified MCP bearer token / JWT. Used to wrap\n * `entry.run()` and `config.askAgent()` calls in `runWithRequestContext`\n * so downstream tools (db-query, accessFilter, resolveCredential) honour\n * per-user / per-org scoping. Without this wrap the MCP endpoint would\n * silently bypass tenant isolation. See finding #6 in\n * /tmp/security-audit/12-mcp-a2a-agent.md.\n */\nexport interface MCPCallerIdentity {\n userEmail: string | undefined;\n orgDomain: string | undefined;\n /** Present only for standard remote MCP OAuth access tokens. */\n oauthScopes?: string[];\n /** Present only for standard remote MCP OAuth access tokens. */\n oauthClientId?: string;\n}\n\n/** Per-request context used to turn an action's relative deep link into the\n * absolute web URL (and desktop `agentnative://` URL) the external agent\n * surfaces. Derived from the inbound request headers in `mountMCP`, or from\n * the resolved local app origin in the stdio standalone path. */\nexport interface MCPRequestMeta {\n /** Origin of the running app, e.g. `http://localhost:8100`. */\n origin?: string;\n /** Optional client preference for which URL the *markdown* link uses. */\n target?: \"browser\" | \"desktop\" | \"terminal\";\n /**\n * The caller authenticated with a real credential (verified A2A/connect\n * JWT, matching ACCESS_TOKEN, or a forwarded owner-email header from\n * `agent-native mcp install`) — not the unauthenticated local dev-open\n * path. When true, `createMCPServerForRequest` serves\n * `config.productionActions` (the full surface) instead of the sparse dev\n * `config.actions`. Set by `mountMCP` from `verifyAuth`.\n */\n fullSurface?: boolean;\n}\n\ntype McpOAuthScope = (typeof MCP_OAUTH_SCOPES)[number];\n\nfunction isActionVisibleForOAuthScope(\n entry: ActionEntry,\n scopes: string[] | undefined,\n): boolean {\n if (!scopes) return true;\n const required: McpOAuthScope =\n entry.readOnly === true ? \"mcp:read\" : \"mcp:write\";\n return hasMcpOAuthScope(scopes, required);\n}\n\nconst COMPACT_MCP_APP_CATALOG_BUILTINS = new Set([\n \"list_apps\",\n \"open_app\",\n \"create_embed_session\",\n]);\n\nfunction isDispatchConfig(config: MCPConfig): boolean {\n const id = (config.appId ?? \"\").toLowerCase();\n const name = (config.name ?? \"\").toLowerCase();\n return id === \"dispatch\" || name.includes(\"dispatch\");\n}\n\nfunction isActionAdvertisedInCompactMcpAppCatalog(\n config: MCPConfig,\n name: string,\n entry: ActionEntry,\n): boolean {\n if (COMPACT_MCP_APP_CATALOG_BUILTINS.has(name)) return true;\n if (name === \"ask_app\" && isDispatchConfig(config)) return true;\n return Boolean(entry.mcpApp?.resource);\n}\n\nconst MCP_APP_OAUTH_CLIENT_RE = /\\b(chatgpt|openai|claude|anthropic)\\b/i;\nconst NON_APP_OAUTH_CLIENT_RE =\n /\\b(code|desktop|cli|cursor|codex|goose|postman|mcpjam|inspector)\\b/i;\nconst MCP_APP_OAUTH_REDIRECT_HOST_RE =\n /(^|\\.)((chatgpt|openai)\\.com|claude\\.ai|anthropic\\.com)$/i;\n\nasync function isKnownMcpAppOAuthClient(\n identity: MCPCallerIdentity | undefined,\n): Promise<boolean> {\n const clientId = identity?.oauthClientId?.trim();\n if (!clientId) return false;\n\n function isKnownAppClientName(value: string | undefined | null): boolean {\n if (!value) return false;\n return (\n MCP_APP_OAUTH_CLIENT_RE.test(value) &&\n !NON_APP_OAUTH_CLIENT_RE.test(value)\n );\n }\n\n function isKnownNonAppClientName(value: string | undefined | null): boolean {\n return Boolean(value && NON_APP_OAUTH_CLIENT_RE.test(value));\n }\n\n function isKnownMcpAppRedirectUri(uri: string): boolean {\n try {\n const url = new URL(uri);\n return (\n url.protocol === \"https:\" &&\n MCP_APP_OAUTH_REDIRECT_HOST_RE.test(url.hostname)\n );\n } catch {\n return false;\n }\n }\n\n if (isKnownAppClientName(clientId)) return true;\n if (isKnownNonAppClientName(clientId)) return false;\n\n try {\n const { getOAuthClient } = await import(\"./oauth-store.js\");\n const client = await getOAuthClient(clientId);\n // If the token carries an OAuth client id but its registration is missing,\n // keep the model on the compact MCP Apps surface instead of exposing every\n // private action/schema.\n if (!client) return true;\n if (isKnownAppClientName(client.clientName)) return true;\n if (isKnownNonAppClientName(client.clientName)) return false;\n if (client.redirectUris.some(isKnownMcpAppRedirectUri)) return true;\n // Most OAuth hosts are UI-oriented MCP clients. Preserve the full catalog\n // only for known code/CLI clients so unknown browser hosts cannot trigger\n // massive resources/list payloads.\n return true;\n } catch {\n // On metadata lookup errors, fail compact instead of falling back to the\n // full action surface; ChatGPT/Claude old tokens otherwise get huge lists.\n return true;\n }\n}\n\ninterface ResolvedMcpAppResource {\n uri: string;\n legacyUris?: string[];\n name: string;\n title?: string;\n description?: string;\n html: ActionMcpAppResourceConfig[\"html\"];\n mimeType: typeof MCP_APP_MIME_TYPE;\n _meta?: Record<string, unknown>;\n}\n\ninterface McpAppResourceContext {\n actionName: string;\n appId?: string;\n requestOrigin?: string;\n}\n\ninterface VersionedMcpAppResourceUri {\n uri: string;\n legacyUris?: string[];\n}\n\nfunction metadataObject(value: unknown): Record<string, unknown> {\n return value && typeof value === \"object\" && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : {};\n}\n\nfunction withMcpChatBridgeParam(urlOrPath: string): string {\n try {\n const base = \"http://agent-native.invalid\";\n const url = urlOrPath.startsWith(\"/\")\n ? new URL(urlOrPath, base)\n : new URL(urlOrPath);\n url.searchParams.set(MCP_APP_CHAT_BRIDGE_QUERY_PARAM, \"1\");\n return urlOrPath.startsWith(\"/\")\n ? `${url.pathname}${url.search}${url.hash}`\n : url.toString();\n } catch {\n return urlOrPath;\n }\n}\n\nfunction mcpAppEmbedOpenLinkMeta(\n result: unknown,\n resource: ResolvedMcpAppResource,\n meta: MCPRequestMeta | undefined,\n): Record<string, unknown> {\n const out = metadataObject(result);\n const embedStartUrl =\n typeof out.embedStartUrl === \"string\"\n ? out.embedStartUrl\n : out.embed === true &&\n typeof out.url === \"string\" &&\n out.url.includes(\"/_agent-native/embed/start\")\n ? out.url\n : null;\n if (!embedStartUrl) return {};\n\n const webUrl = toAbsoluteOpenUrl(\n withMcpChatBridgeParam(embedStartUrl),\n meta?.origin,\n );\n const deepLinkUrl =\n typeof out.deepLinkUrl === \"string\" ? out.deepLinkUrl : null;\n const fallbackLabel = resource.title ?? resource.name ?? \"app\";\n const label =\n typeof out.app === \"string\" && out.app.trim()\n ? `Open ${out.app.trim()}`\n : fallbackLabel;\n const view =\n typeof out.view === \"string\" && out.view.trim()\n ? out.view.trim()\n : typeof out.path === \"string\" && out.path.trim()\n ? out.path.trim()\n : undefined;\n\n return {\n \"agent-native/openLink\": {\n label,\n ...(view ? { view } : {}),\n webUrl,\n desktopUrl: deepLinkUrl\n ? toAbsoluteOpenUrl(deepLinkUrl, meta?.origin)\n : webUrl,\n },\n };\n}\n\n/**\n * Build the deep-link content block + structured `_meta` for a tool result.\n * Best-effort: any throw / nullish link is swallowed so a bad `link` builder\n * never fails the tool call.\n */\nexport function buildLinkArtifacts(\n entry: ActionEntry,\n args: Record<string, any>,\n result: any,\n meta: MCPRequestMeta | undefined,\n): {\n block?: { type: \"text\"; text: string };\n _meta?: Record<string, unknown>;\n} {\n if (typeof entry.link !== \"function\") return {};\n try {\n const lk = entry.link({ args: args ?? {}, result });\n if (!lk?.url) return {};\n const linkUrl = isAgentNativeOpenDeepLink(lk.url)\n ? withCollapsedAgentSidebarParam(lk.url)\n : lk.url;\n const webUrl = toAbsoluteOpenUrl(linkUrl, meta?.origin);\n const desktopUrl = toDesktopOpenUrl(linkUrl);\n const markdownUrl = meta?.target === \"desktop\" ? desktopUrl : webUrl;\n return {\n block: { type: \"text\", text: `\\n\\n[${lk.label} →](${markdownUrl})` },\n _meta: {\n \"agent-native/openLink\": {\n label: lk.label,\n view: lk.view,\n webUrl,\n desktopUrl,\n },\n },\n };\n } catch {\n return {};\n }\n}\n\n/**\n * Merge the generic cross-app builtin tools into the config's action\n * registry. **Template actions take precedence**: if a template defines an\n * action with the same name as a builtin (e.g. its own `list_apps`), the\n * template entry wins and the builtin is dropped. This mirrors the\n * template-over-workspace-core precedence in `autoDiscoverActions`.\n *\n * The builtins are pure-ish navigators / scaffolders; they call back into the\n * same `config.actions` / `config.askAgent` so there is no second agent loop.\n */\nfunction mergeBuiltinTools(\n config: MCPConfig,\n baseActions: Record<string, ActionEntry>,\n requestMeta?: MCPRequestMeta,\n): Record<string, ActionEntry> {\n if (config.builtinCrossAppTools === false) return baseActions;\n const builtins = getBuiltinCrossAppTools(config, requestMeta);\n const merged: Record<string, ActionEntry> = { ...builtins };\n // Template / app actions overwrite same-named builtins.\n for (const [name, entry] of Object.entries(baseActions)) {\n merged[name] = entry;\n }\n return merged;\n}\n\nfunction safeUiSegment(value: string | undefined, fallback: string): string {\n const normalized = (value || fallback)\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9._-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n return normalized || fallback;\n}\n\n// ChatGPT and Claude cache MCP App resource HTML by `ui://` URI. Bump this\n// when the shared shell changes in a way that must invalidate host caches.\nconst MCP_APP_RESOURCE_SHELL_VERSION = \"shell-v25\";\n\nfunction legacyDefaultMcpAppUri(config: MCPConfig, actionName: string): string {\n const app = safeUiSegment(config.appId ?? config.name, \"agent-native\");\n const action = safeUiSegment(actionName, \"tool\");\n return `ui://${app}/${action}`;\n}\n\nfunction versionMcpAppResourceUri(\n rawUri: string,\n): VersionedMcpAppResourceUri | null {\n const uri = rawUri.trim();\n if (!uri.startsWith(\"ui://\")) return null;\n const versionSuffix = `/${MCP_APP_RESOURCE_SHELL_VERSION}`;\n let versionedUri: string;\n try {\n const parsed = new URL(uri);\n const path = parsed.pathname.replace(/\\/+$/g, \"\");\n parsed.pathname = /\\/shell-v\\d+$/.test(path)\n ? path.replace(/\\/shell-v\\d+$/, versionSuffix)\n : `${path}${versionSuffix}`;\n versionedUri = parsed.toString();\n } catch {\n return null;\n }\n return {\n uri: versionedUri,\n ...(versionedUri !== uri ? { legacyUris: [uri] } : {}),\n };\n}\n\nfunction getMcpAppResourceUri(\n config: MCPConfig,\n actionName: string,\n entry: ActionEntry,\n): VersionedMcpAppResourceUri | null {\n const resource = entry.mcpApp?.resource;\n if (!resource) return null;\n const baseUri =\n resource.uri?.trim() || legacyDefaultMcpAppUri(config, actionName);\n return versionMcpAppResourceUri(baseUri);\n}\n\nfunction expandRequestOriginSources(\n sources: string[] | undefined,\n requestMeta?: MCPRequestMeta,\n): string[] | undefined {\n if (!sources) return undefined;\n const origin = requestMeta?.origin;\n return sources.flatMap((source) =>\n source === MCP_APP_REQUEST_ORIGIN_CSP_SOURCE && origin\n ? [origin]\n : [source],\n );\n}\n\nfunction openAiWidgetCsp(\n cspConfig: ActionMcpAppCsp | undefined,\n requestMeta?: MCPRequestMeta,\n): Record<string, string[]> | undefined {\n if (!cspConfig) return undefined;\n const csp: Record<string, string[]> = {};\n const connectDomains = expandRequestOriginSources(\n cspConfig.connectDomains,\n requestMeta,\n );\n const resourceDomains = expandRequestOriginSources(\n cspConfig.resourceDomains,\n requestMeta,\n );\n const frameDomains = expandRequestOriginSources(\n cspConfig.frameDomains,\n requestMeta,\n );\n if (connectDomains?.length) csp.connect_domains = connectDomains;\n if (resourceDomains?.length) csp.resource_domains = resourceDomains;\n if (frameDomains?.length) csp.frame_domains = frameDomains;\n return Object.keys(csp).length > 0 ? csp : undefined;\n}\n\nfunction mcpAppUiMeta(\n resource: ActionMcpAppResourceConfig,\n resolvedCsp: ActionMcpAppCsp | undefined,\n requestMeta?: MCPRequestMeta,\n description?: string,\n): Record<string, unknown> | undefined {\n const base =\n resource._meta && typeof resource._meta === \"object\"\n ? { ...resource._meta }\n : {};\n const existingUi =\n base.ui && typeof base.ui === \"object\" && !Array.isArray(base.ui)\n ? (base.ui as Record<string, unknown>)\n : {};\n const ui: Record<string, unknown> = { ...existingUi };\n if (resolvedCsp) {\n ui.csp = {\n ...resolvedCsp,\n connectDomains: expandRequestOriginSources(\n resolvedCsp.connectDomains,\n requestMeta,\n ),\n resourceDomains: expandRequestOriginSources(\n resolvedCsp.resourceDomains,\n requestMeta,\n ),\n frameDomains: expandRequestOriginSources(\n resolvedCsp.frameDomains,\n requestMeta,\n ),\n baseUriDomains: expandRequestOriginSources(\n resolvedCsp.baseUriDomains,\n requestMeta,\n ),\n };\n }\n if (resource.permissions) ui.permissions = resource.permissions;\n if (resource.domain) ui.domain = resource.domain;\n if (typeof resource.prefersBorder === \"boolean\") {\n ui.prefersBorder = resource.prefersBorder;\n }\n if (Object.keys(ui).length > 0) base.ui = ui;\n if (description && base[\"openai/widgetDescription\"] == null) {\n base[\"openai/widgetDescription\"] = description;\n }\n if (\n typeof resource.prefersBorder === \"boolean\" &&\n base[\"openai/widgetPrefersBorder\"] == null\n ) {\n base[\"openai/widgetPrefersBorder\"] = resource.prefersBorder;\n }\n const openAiCsp = openAiWidgetCsp(resolvedCsp, requestMeta);\n if (openAiCsp && base[\"openai/widgetCSP\"] == null) {\n base[\"openai/widgetCSP\"] = openAiCsp;\n }\n return Object.keys(base).length > 0 ? base : undefined;\n}\n\nasync function resolveMcpAppCsp(\n resource: ActionMcpAppResourceConfig,\n ctx: McpAppResourceContext,\n): Promise<ActionMcpAppCsp | undefined> {\n if (!resource.csp) return undefined;\n return typeof resource.csp === \"function\"\n ? await resource.csp(ctx)\n : resource.csp;\n}\n\nasync function resolveMcpAppResource(\n config: MCPConfig,\n actionName: string,\n entry: ActionEntry,\n requestMeta?: MCPRequestMeta,\n): Promise<ResolvedMcpAppResource | null> {\n const resource = entry.mcpApp?.resource;\n if (!resource) return null;\n const resolvedUri = getMcpAppResourceUri(config, actionName, entry);\n if (!resolvedUri) return null;\n const description = resource.description ?? entry.tool.description;\n const resolvedCsp = await resolveMcpAppCsp(resource, {\n actionName,\n appId: config.appId,\n requestOrigin: requestMeta?.origin,\n });\n const resourceMeta = mcpAppUiMeta(\n resource,\n resolvedCsp,\n requestMeta,\n description,\n );\n return {\n uri: resolvedUri.uri,\n ...(resolvedUri.legacyUris ? { legacyUris: resolvedUri.legacyUris } : {}),\n name: resource.name?.trim() || actionName,\n ...(resource.title ? { title: resource.title } : {}),\n ...(description ? { description } : {}),\n html: resource.html,\n mimeType: resource.mimeType ?? MCP_APP_MIME_TYPE,\n ...(resourceMeta ? { _meta: resourceMeta } : {}),\n };\n}\n\nasync function resolveMcpAppResourceSafely(\n config: MCPConfig,\n actionName: string,\n entry: ActionEntry,\n requestMeta?: MCPRequestMeta,\n): Promise<ResolvedMcpAppResource | null> {\n try {\n return await resolveMcpAppResource(config, actionName, entry, requestMeta);\n } catch (error) {\n console.warn(\n `[mcp] Skipping MCP App resource for action \"${actionName}\" because its metadata could not be resolved.`,\n error,\n );\n return null;\n }\n}\n\nasync function getMcpAppResources(\n config: MCPConfig,\n actions: Record<string, ActionEntry>,\n requestMeta?: MCPRequestMeta,\n): Promise<ResolvedMcpAppResource[]> {\n const resources = await Promise.all(\n Object.entries(actions).map(([name, entry]) =>\n resolveMcpAppResourceSafely(config, name, entry, requestMeta),\n ),\n );\n return resources.filter((resource): resource is ResolvedMcpAppResource =>\n Boolean(resource),\n );\n}\n\nfunction renderMcpAppHtml(\n resource: ResolvedMcpAppResource,\n actionName: string,\n config: MCPConfig,\n requestMeta?: MCPRequestMeta,\n): string {\n if (typeof resource.html === \"function\") {\n return resource.html({\n actionName,\n appId: config.appId,\n requestOrigin: requestMeta?.origin,\n });\n }\n return resource.html;\n}\n\nfunction openAiToolDescriptorMeta(\n resource: ResolvedMcpAppResource,\n): Record<string, unknown> {\n const label = resource.title ?? resource.name;\n const widgetCsp = metadataObject(resource._meta?.[\"openai/widgetCSP\"]);\n return {\n \"openai/outputTemplate\": resource.uri,\n \"openai/toolInvocation/invoking\": `Opening ${label}`,\n \"openai/toolInvocation/invoked\": `${label} ready`,\n \"openai/widgetAccessible\": true,\n ...(Object.keys(widgetCsp).length > 0\n ? { \"openai/widgetCSP\": widgetCsp }\n : {}),\n };\n}\n\nfunction openAiToolResultMeta(\n resource: ResolvedMcpAppResource,\n): Record<string, unknown> {\n const label = resource.title ?? resource.name;\n const widgetCsp = metadataObject(resource._meta?.[\"openai/widgetCSP\"]);\n return {\n \"openai/outputTemplate\": resource.uri,\n \"openai/toolInvocation/invoking\": `Opening ${label}`,\n \"openai/toolInvocation/invoked\": `${label} ready`,\n \"openai/widgetAccessible\": true,\n ...(Object.keys(widgetCsp).length > 0\n ? { \"openai/widgetCSP\": widgetCsp }\n : {}),\n };\n}\n\nfunction mcpAppToolUiMeta(\n resource: ResolvedMcpAppResource,\n visibility: unknown,\n): Record<string, unknown> {\n return {\n resourceUri: resource.uri,\n visibility: Array.isArray(visibility) ? visibility : [\"model\", \"app\"],\n };\n}\n\nfunction primitiveValue(value: unknown): value is string | number | boolean {\n return (\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\"\n );\n}\n\nfunction mcpAppStructuredContent(\n result: unknown,\n meta: Record<string, unknown> | undefined,\n): Record<string, unknown> {\n const out: Record<string, unknown> =\n result && typeof result === \"object\" && !Array.isArray(result)\n ? { ...(result as Record<string, unknown>) }\n : primitiveValue(result)\n ? { result }\n : {};\n const openLink = meta?.[\"agent-native/openLink\"];\n if (openLink && typeof openLink === \"object\" && !Array.isArray(openLink)) {\n out.openLink = openLink;\n const webUrl = (openLink as Record<string, unknown>).webUrl;\n if (typeof webUrl === \"string\" && !out.url) out.url = webUrl;\n }\n return Object.keys(out).length > 0 ? out : { status: \"ok\" };\n}\n\nfunction truncateToolText(value: string, max = 2000): string {\n if (value.length <= max) return value;\n return `${value.slice(0, max - 1)}…`;\n}\n\nfunction conciseMcpAppToolText(\n name: string,\n result: unknown,\n structuredContent: Record<string, unknown>,\n): string {\n if (typeof result === \"string\") return truncateToolText(result);\n const message = structuredContent.message;\n if (typeof message === \"string\" && message.trim()) {\n return truncateToolText(message.trim());\n }\n const title = structuredContent.title ?? structuredContent.name;\n if (typeof title === \"string\" && title.trim()) {\n return `${title.trim()} is ready.`;\n }\n const id = structuredContent.id;\n if (typeof id === \"string\" && id.trim()) {\n return `${name} completed for ${id.trim()}.`;\n }\n return `${name} completed.`;\n}\n\n// ---------------------------------------------------------------------------\n// MCP Server creation — converts ActionEntry registry to MCP tools\n// ---------------------------------------------------------------------------\n\n/**\n * Build a fully-wired MCP `Server` for a single request / session.\n *\n * Shared by the stateless Streamable-HTTP mount (`mountMCP`) and the stdio\n * standalone transport. The HTTP mount passes the per-request origin via\n * `requestMeta`; the stdio standalone path passes the resolved local app\n * origin so deep links still become absolute URLs.\n */\nexport async function createMCPServerForRequest(\n config: MCPConfig,\n identity: MCPCallerIdentity | undefined,\n requestMeta?: MCPRequestMeta,\n) {\n const { Server } = await import(\"@modelcontextprotocol/sdk/server/index.js\");\n const {\n ListToolsRequestSchema,\n CallToolRequestSchema,\n ListResourcesRequestSchema,\n ReadResourceRequestSchema,\n ListResourceTemplatesRequestSchema,\n } = await import(\"@modelcontextprotocol/sdk/types.js\");\n\n // Resolve the effective caller identity. JWT / header-derived identity\n // (passed by `mountMCP` via `verifyAuth`) wins. When the caller passed no\n // identity — the stdio **standalone** path — fall back to the\n // `AGENT_NATIVE_OWNER_EMAIL` env the `agent-native mcp install` flow writes\n // into the `agent-native mcp serve` process env, so standalone tool runs are\n // tenant-scoped to the configured owner instead of running unscoped. Stays\n // undefined for true dev-open (no token, no secret, no owner) — behavior\n // there is unchanged.\n const ownerFromEnv = process.env.AGENT_NATIVE_OWNER_EMAIL?.trim();\n const effectiveIdentity: MCPCallerIdentity | undefined =\n identity ??\n (ownerFromEnv\n ? { userEmail: ownerFromEnv, orgDomain: undefined }\n : undefined);\n\n // The action set the request handlers operate on = base actions + generic\n // cross-app builtins (template wins on name collision). An authenticated\n // real caller (connect-minted token / `mcp install` owner / production —\n // `requestMeta.fullSurface`, or the stdio standalone path identified by\n // `AGENT_NATIVE_OWNER_EMAIL`) gets the full `productionActions` surface\n // even in local dev; the unauthenticated dev-open path keeps the sparse\n // `config.actions`. See `external-agents` skill, \"Dev vs production tool\n // surface\".\n const useFullSurface = requestMeta?.fullSurface === true || !!ownerFromEnv;\n const baseActions =\n useFullSurface && config.productionActions\n ? config.productionActions\n : config.actions;\n const actions = mergeBuiltinTools(config, baseActions, requestMeta);\n const visibleActions = Object.fromEntries(\n Object.entries(actions).filter(([, entry]) =>\n isActionVisibleForOAuthScope(entry, effectiveIdentity?.oauthScopes),\n ),\n );\n const compactMcpAppCatalog =\n (Array.isArray(effectiveIdentity?.oauthScopes) &&\n hasMcpOAuthScope(effectiveIdentity.oauthScopes, \"mcp:apps\")) ||\n (await isKnownMcpAppOAuthClient(effectiveIdentity));\n const advertisedActions = compactMcpAppCatalog\n ? Object.fromEntries(\n Object.entries(visibleActions).filter(([name, entry]) =>\n isActionAdvertisedInCompactMcpAppCatalog(config, name, entry),\n ),\n )\n : visibleActions;\n const supportsMcpApps =\n compactMcpAppCatalog &&\n Object.values(advertisedActions).some((entry) =>\n Boolean(entry.mcpApp?.resource),\n );\n const server = new Server(\n { name: config.name, version: config.version ?? \"1.0.0\" },\n {\n capabilities: {\n tools: {},\n ...(supportsMcpApps\n ? {\n resources: {},\n extensions: {\n [MCP_APP_EXTENSION_ID]: {\n mimeTypes: [MCP_APP_MIME_TYPE],\n },\n },\n }\n : {}),\n },\n },\n );\n\n // Resolve orgId once per request (DB lookup) so subsequent wraps are\n // synchronous. The caller identity may be undefined for true dev-open —\n // in that case we run with no userEmail/orgId, which makes downstream\n // tools that require per-user scope return empty results rather than\n // cross-tenant data (the safe default).\n const orgIdPromise = resolveOrgIdFromDomain(effectiveIdentity?.orgDomain);\n\n /**\n * Wrap a callback in\n * `runWithRequestContext({ userEmail, orgId, requestOrigin }, fn)`.\n * Both the tools/list and tools/call handlers go through this so\n * downstream `accessFilter`, `resolveCredential`, and per-user MCP\n * visibility checks see the verified caller's identity. `requestOrigin`\n * is the live server origin derived from the inbound request (same value\n * used to absolutize deep links) so actions that build fetchable URLs\n * (e.g. design `export-coding-handoff`'s signed raw-code URL) resolve the\n * correct local-workspace origin instead of a prod/localhost fallback.\n */\n async function withCallerContext<T>(fn: () => Promise<T>): Promise<T> {\n const orgId = await orgIdPromise;\n return runWithRequestContext(\n {\n userEmail: effectiveIdentity?.userEmail,\n orgId,\n ...(requestMeta?.origin ? { requestOrigin: requestMeta.origin } : {}),\n },\n fn,\n ) as Promise<T>;\n }\n\n // tools/list — return all actions + ask-agent meta-tool. Wrapped in the\n // request context so per-user MCP visibility (mcp-client/visibility.ts)\n // applies to the listing too.\n server.setRequestHandler(ListToolsRequestSchema, async () => {\n return withCallerContext(async () => {\n const tools = await Promise.all(\n Object.entries(advertisedActions).map(async ([name, entry]) => {\n const hasLink = typeof entry.link === \"function\";\n const mcpAppResource = await resolveMcpAppResourceSafely(\n config,\n name,\n entry,\n requestMeta,\n );\n const rawToolMeta =\n (entry.tool as any)._meta &&\n typeof (entry.tool as any)._meta === \"object\" &&\n !Array.isArray((entry.tool as any)._meta)\n ? { ...((entry.tool as any)._meta as Record<string, unknown>) }\n : {};\n const toolMeta = {\n ...rawToolMeta,\n ...(mcpAppResource\n ? {\n ...openAiToolDescriptorMeta(mcpAppResource),\n [MCP_APP_RESOURCE_URI_META_KEY]: mcpAppResource.uri,\n ui: mcpAppToolUiMeta(\n mcpAppResource,\n entry.mcpApp?.visibility ??\n metadataObject(rawToolMeta.ui).visibility,\n ),\n }\n : {}),\n };\n const baseDescription = entry.tool.description ?? name;\n const annotations: Record<string, unknown> = {\n readOnlyHint: entry.readOnly === true,\n destructiveHint: entry.publicAgent?.isConsequential === true,\n openWorldHint: false,\n };\n if (hasLink) annotations[\"agent-native/producesOpenLink\"] = true;\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 ...(Object.keys(toolMeta).length > 0 ? { _meta: toolMeta } : {}),\n annotations,\n };\n }),\n );\n\n if (\n !compactMcpAppCatalog &&\n config.askAgent &&\n hasMcpOAuthScope(effectiveIdentity?.oauthScopes, \"mcp:write\")\n ) {\n tools.push({\n name: \"ask-agent\",\n description:\n \"Send a natural-language message to the app's AI agent and get a response. \" +\n \"Use this for complex, multi-step tasks that require the agent's reasoning \" +\n \"and full context about the app.\",\n inputSchema: {\n type: \"object\" as const,\n properties: {\n message: {\n type: \"string\",\n description: \"The message to send to the agent\",\n },\n },\n required: [\"message\"],\n },\n annotations: {\n readOnlyHint: false,\n destructiveHint: false,\n openWorldHint: false,\n },\n });\n }\n\n return { tools };\n });\n });\n\n // tools/call — dispatch to action registry or ask-agent. Wrapped in the\n // request context so the action's `run(args)` and `askAgent()` execute\n // with the verified caller's identity, not the platform default.\n server.setRequestHandler(CallToolRequestSchema, async (request: any) => {\n return withCallerContext(async () => {\n const { name, arguments: args } = request.params;\n\n if (name === \"ask-agent\" && config.askAgent) {\n if (compactMcpAppCatalog) {\n return {\n content: [{ type: \"text\", text: `Unknown tool: ${name}` }],\n isError: true,\n };\n }\n if (!hasMcpOAuthScope(effectiveIdentity?.oauthScopes, \"mcp:write\")) {\n return {\n content: [\n {\n type: \"text\",\n text: \"Forbidden: OAuth scope does not allow ask-agent\",\n },\n ],\n isError: true,\n };\n }\n const message = args?.message ?? \"\";\n try {\n const result = await config.askAgent(message);\n return { content: [{ type: \"text\", text: result }] };\n } catch (err: any) {\n return {\n content: [{ type: \"text\", text: `Error: ${err.message}` }],\n isError: true,\n };\n }\n }\n\n const callableActions = compactMcpAppCatalog\n ? advertisedActions\n : actions;\n const entry = callableActions[name];\n if (!entry) {\n return {\n content: [{ type: \"text\", text: `Unknown tool: ${name}` }],\n isError: true,\n };\n }\n if (\n !isActionVisibleForOAuthScope(entry, effectiveIdentity?.oauthScopes)\n ) {\n return {\n content: [\n {\n type: \"text\",\n text: `Forbidden: OAuth scope does not allow tool ${name}`,\n },\n ],\n isError: true,\n };\n }\n\n try {\n const result = await entry.run((args as Record<string, string>) ?? {});\n const rawResult = isMcpActionResult(result) ? result.raw : result;\n const resultForClient = isMcpActionResult(result)\n ? result.text\n : result;\n const mcpAppResource = await resolveMcpAppResourceSafely(\n config,\n name,\n entry,\n requestMeta,\n );\n const { block, _meta } = buildLinkArtifacts(\n entry,\n (args as Record<string, any>) ?? {},\n rawResult,\n requestMeta,\n );\n const responseMeta: Record<string, unknown> = {\n ...(_meta ?? {}),\n ...(mcpAppResource\n ? mcpAppEmbedOpenLinkMeta(rawResult, mcpAppResource, requestMeta)\n : {}),\n ...(mcpAppResource ? openAiToolResultMeta(mcpAppResource) : {}),\n };\n const structuredContent = mcpAppResource\n ? mcpAppStructuredContent(rawResult, responseMeta)\n : undefined;\n const text = mcpAppResource\n ? conciseMcpAppToolText(name, resultForClient, structuredContent!)\n : typeof resultForClient === \"string\"\n ? resultForClient\n : JSON.stringify(resultForClient);\n const content: any[] = [{ type: \"text\", text }];\n if (block) content.push(block);\n return {\n content,\n ...(structuredContent ? { structuredContent } : {}),\n ...(Object.keys(responseMeta).length > 0\n ? { _meta: responseMeta }\n : {}),\n };\n } catch (err: any) {\n return {\n content: [{ type: \"text\", text: `Error: ${err.message}` }],\n isError: true,\n };\n }\n });\n });\n\n if (supportsMcpApps) {\n server.setRequestHandler(ListResourcesRequestSchema, async () => {\n return withCallerContext(async () => {\n const mcpAppResources = await getMcpAppResources(\n config,\n advertisedActions,\n requestMeta,\n );\n return {\n resources: mcpAppResources.map((resource) => ({\n uri: resource.uri,\n name: resource.name,\n ...(resource.title ? { title: resource.title } : {}),\n ...(resource.description\n ? { description: resource.description }\n : {}),\n mimeType: resource.mimeType,\n ...(resource._meta ? { _meta: resource._meta } : {}),\n })),\n };\n });\n });\n\n server.setRequestHandler(ListResourceTemplatesRequestSchema, async () => {\n return withCallerContext(async () => {\n const mcpAppResources = await getMcpAppResources(\n config,\n advertisedActions,\n requestMeta,\n );\n return {\n resourceTemplates: mcpAppResources.map((resource) => ({\n uriTemplate: resource.uri,\n name: resource.name,\n ...(resource.title ? { title: resource.title } : {}),\n ...(resource.description\n ? { description: resource.description }\n : {}),\n mimeType: resource.mimeType,\n ...(resource._meta ? { _meta: resource._meta } : {}),\n })),\n };\n });\n });\n\n server.setRequestHandler(\n ReadResourceRequestSchema,\n async (request: any) => {\n return withCallerContext(async () => {\n const uri = request.params?.uri;\n let found: {\n actionName: string;\n resource: ResolvedMcpAppResource;\n } | null = null;\n for (const [name, entry] of Object.entries(advertisedActions)) {\n const resourceUri = getMcpAppResourceUri(config, name, entry);\n if (\n !resourceUri ||\n (resourceUri.uri !== uri &&\n !resourceUri.legacyUris?.includes(uri))\n ) {\n continue;\n }\n const resource = await resolveMcpAppResourceSafely(\n config,\n name,\n entry,\n requestMeta,\n );\n if (resource) {\n found = { actionName: name, resource };\n }\n break;\n }\n if (!found) {\n throw new Error(`MCP App resource not found: ${uri}`);\n }\n return {\n contents: [\n {\n uri,\n mimeType: found.resource.mimeType,\n text: renderMcpAppHtml(\n found.resource,\n found.actionName,\n config,\n requestMeta,\n ),\n ...(found.resource._meta\n ? { _meta: found.resource._meta }\n : {}),\n },\n ],\n };\n });\n },\n );\n }\n\n return server;\n}\n\n// ---------------------------------------------------------------------------\n// Auth — reuses the same pattern as A2A (Bearer token or JWT). Shared so the\n// HTTP mount and any stdio-side auth-aware helper resolve identity identically.\n// ---------------------------------------------------------------------------\n\nexport function getAccessTokens(): string[] {\n const single = process.env.ACCESS_TOKEN;\n const multi = process.env.ACCESS_TOKENS;\n const tokens: string[] = [];\n if (single) tokens.push(single);\n if (multi) {\n tokens.push(\n ...multi\n .split(\",\")\n .map((t) => t.trim())\n .filter(Boolean),\n );\n }\n return tokens;\n}\n\n/**\n * Resolve the caller identity for a static-token (or dev-open) auth path.\n *\n * Static `ACCESS_TOKEN` / `ACCESS_TOKENS` auth carries no per-caller claims,\n * so without this the MCP endpoint would run every tool with\n * `userEmail === undefined` and per-user / per-org scoped actions\n * (`accessFilter`, `resolveAccess`, `resolveCredential`) would return\n * empty / wrong data. The `agent-native mcp install` flow writes\n * `AGENT_NATIVE_OWNER_EMAIL` into the client config env and the stdio proxy\n * forwards it as the `X-Agent-Native-Owner-Email` request header (see\n * `mcp/stdio.ts#authHeaders`). We trust that owner hint *only* on the\n * static-token path — JWT auth already carries a cryptographically verified\n * `sub`, so the header is ignored there and never widens JWT scope.\n *\n * Precedence is server-trusted-first: the server process's\n * `AGENT_NATIVE_OWNER_EMAIL` env (set out-of-band by the operator / deploy)\n * ALWAYS wins, and a client-supplied `X-Agent-Native-Owner-Email` header is\n * honored *only as a fallback when that env is unset*. A static `ACCESS_TOKEN`\n * is a shared bearer secret; letting a request header override a\n * server-configured owner would let anyone holding a leaked token act as any\n * user. The header path remains for the single-tenant local-dev install flow\n * where the app server process has no owner env and the token *is* the\n * workspace secret; multi-tenant deployments must use A2A JWT (verified `sub`),\n * not a static token, for per-user scope.\n *\n * Returns `undefined` when no owner email is available (true dev-open: no\n * token, no secret, no owner) so behavior there stays unchanged.\n */\nfunction deriveStaticTokenIdentity(\n ownerEmailHeader: string | undefined,\n): MCPCallerIdentity | undefined {\n const owner =\n process.env.AGENT_NATIVE_OWNER_EMAIL?.trim() ||\n (typeof ownerEmailHeader === \"string\" && ownerEmailHeader.trim()) ||\n \"\";\n if (!owner) return undefined;\n return { userEmail: owner, orgDomain: undefined };\n}\n\nfunction addSecretCandidate(\n candidates: string[],\n secret: string | null | undefined,\n): void {\n const trimmed = secret?.trim();\n if (!trimmed || candidates.includes(trimmed)) return;\n candidates.push(trimmed);\n}\n\nasync function verifyA2AJwtForMcp(\n token: string,\n): Promise<Record<string, unknown> | null> {\n const jose = await import(\"jose\");\n let unverifiedPayload: Record<string, unknown> | null = null;\n try {\n unverifiedPayload = jose.decodeJwt(token) as Record<string, unknown>;\n } catch {\n return null;\n }\n\n const candidateSecrets: string[] = [];\n addSecretCandidate(candidateSecrets, process.env.A2A_SECRET);\n\n const orgDomain =\n typeof unverifiedPayload.org_domain === \"string\"\n ? unverifiedPayload.org_domain\n : undefined;\n if (orgDomain) {\n try {\n const { getA2ASecretByDomain } = await import(\"../org/context.js\");\n addSecretCandidate(\n candidateSecrets,\n await getA2ASecretByDomain(orgDomain),\n );\n } catch {\n // DB not ready or org lookup unavailable — fall back to other candidates.\n }\n }\n\n for (const secret of candidateSecrets) {\n try {\n const { payload } = await jose.jwtVerify(\n token,\n new TextEncoder().encode(secret),\n );\n return payload as Record<string, unknown>;\n } catch {\n // Try the next candidate without exposing which secret matched.\n }\n }\n\n return null;\n}\n\n/**\n * Verify the inbound auth header. Returns:\n * - { authed: true, identity } when verified — `identity` is derived from\n * the JWT (`sub` / `org_domain`) for JWT auth, or from the\n * `AGENT_NATIVE_OWNER_EMAIL` env / `X-Agent-Native-Owner-Email` header\n * for static-token auth (the `agent-native mcp install` flow). `identity`\n * is undefined only for true dev-open with no owner hint.\n * - { authed: false } on rejection.\n *\n * When A2A_SECRET is set we extract the JWT's `sub` (caller email) and\n * `org_domain` claims so the MCP endpoint can wrap tool runs in\n * `runWithRequestContext({ userEmail, orgId })`. Without that wrap, the\n * MCP endpoint loses tenant identity and downstream `accessFilter` /\n * `resolveCredential` calls fall back to platform-wide defaults.\n *\n * `ownerEmailHeader` is the forwarded `X-Agent-Native-Owner-Email` value; it\n * is consulted ONLY on the static-token / dev-open path (never to influence\n * verified JWT identity), so the install flow runs tools as the configured\n * owner instead of an unscoped anonymous caller.\n */\nexport async function verifyAuth(\n authHeader: string | undefined,\n ownerEmailHeader?: string | undefined,\n options: { allowDevOpen?: boolean; resourceUrl?: string } = {},\n): Promise<{\n authed: boolean;\n identity?: MCPCallerIdentity;\n /**\n * The caller presented a real credential — a verified A2A/connect JWT, a\n * matching ACCESS_TOKEN, or (on the no-auth-configured path) a forwarded\n * owner-email header from `agent-native mcp install`. Drives the full vs\n * sparse MCP tool surface in local dev. The pure unauthenticated dev-open\n * path (no secret, no token, no owner header) is `false`.\n */\n fullSurface?: boolean;\n}> {\n // No auth configured → allow only when the route caller has already\n // established that this is a loopback/local dev request. Still honour an\n // owner hint there so the local install/connect flow stays tenant-scoped.\n const accessTokens = getAccessTokens();\n const hasA2ASecret = !!process.env.A2A_SECRET;\n const token = authHeader?.startsWith(\"Bearer \")\n ? authHeader.slice(7)\n : undefined;\n if (token) {\n const oauthIdentity = await verifyMcpOAuthAccessToken(\n token,\n options.resourceUrl,\n );\n if (oauthIdentity) {\n return {\n authed: true,\n identity: {\n userEmail: oauthIdentity.userEmail,\n orgDomain: oauthIdentity.orgDomain,\n oauthScopes: oauthIdentity.scopes,\n oauthClientId: oauthIdentity.clientId,\n },\n fullSurface: true,\n };\n }\n }\n if (accessTokens.length === 0 && !hasA2ASecret && !token) {\n if (options.allowDevOpen === false) {\n return { authed: false };\n }\n return {\n authed: true,\n identity: deriveStaticTokenIdentity(ownerEmailHeader),\n // `mcp install`'s stdio proxy forwards an owner-email header even when\n // the local app has no secret configured — that is a real, identified\n // caller and gets the full surface. A bare browser/curl dev probe with\n // no owner hint stays on the sparse dev surface.\n fullSurface: !!(ownerEmailHeader && ownerEmailHeader.trim()),\n };\n }\n\n if (!token) return { authed: false };\n\n // Try an A2A JWT via the shared A2A_SECRET first, then the caller org's\n // synced A2A secret when the token carries org_domain.\n const payload = await verifyA2AJwtForMcp(token);\n if (payload) {\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 signature was already\n // cryptographically verified, so failing open here only widens the\n // explicit-revoke gate, never the trust boundary.\n if (tokenScope === MCP_CONNECT_SCOPE) {\n if (typeof payload.jti !== \"string\" || !payload.jti) {\n return { authed: false };\n }\n const jti = payload.jti;\n try {\n const { isJtiRevoked, touchTokenUsed } =\n await import(\"./connect-store.js\");\n if (await isJtiRevoked(jti)) {\n return { authed: false };\n }\n // Best-effort usage telemetry — never blocks / throws.\n void touchTokenUsed(jti);\n } catch {\n // Store import / lookup failed — fail open (see comment above).\n }\n }\n\n return {\n authed: true,\n identity: {\n userEmail: typeof payload.sub === \"string\" ? payload.sub : undefined,\n orgDomain:\n typeof payload.org_domain === \"string\"\n ? (payload.org_domain as string)\n : undefined,\n },\n // Verified JWT (connect-minted or A2A delegation) — a real caller.\n fullSurface: true,\n };\n }\n\n if (accessTokens.length === 0 && !hasA2ASecret) {\n if (options.allowDevOpen === false) {\n return { authed: false };\n }\n return {\n authed: true,\n identity: deriveStaticTokenIdentity(ownerEmailHeader),\n fullSurface: !!(ownerEmailHeader && ownerEmailHeader.trim()),\n };\n }\n\n // Try ACCESS_TOKEN / ACCESS_TOKENS exact match. Static tokens carry no\n // per-caller claims, so derive identity from the forwarded owner-email\n // hint (install flow) — otherwise tools would run unscoped.\n if (accessTokens.length > 0 && accessTokens.includes(token)) {\n return {\n authed: true,\n identity: deriveStaticTokenIdentity(ownerEmailHeader),\n // Matched a configured ACCESS_TOKEN — a real caller.\n fullSurface: true,\n };\n }\n\n return { authed: false };\n}\n\nexport async function resolveOrgIdFromDomain(\n orgDomain: string | undefined,\n): Promise<string | undefined> {\n if (!orgDomain) return undefined;\n try {\n const { resolveOrgByDomain } = await import(\"../org/context.js\");\n const org = await resolveOrgByDomain(orgDomain);\n return org?.orgId ?? undefined;\n } catch {\n return undefined;\n }\n}\n"]}
1
+ {"version":3,"file":"build-server.js","sourceRoot":"","sources":["../../src/mcp/build-server.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAGH,OAAO,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAC;AAChE,OAAO,EACL,oBAAoB,EACpB,iBAAiB,EACjB,6BAA6B,GAG9B,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,iCAAiC,EAAE,MAAM,gBAAgB,CAAC;AACnE,OAAO,EAAE,qBAAqB,EAAE,MAAM,8BAA8B,CAAC;AACrE,OAAO,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC7E,OAAO,EACL,yBAAyB,EACzB,8BAA8B,GAC/B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,+BAA+B,EAAE,MAAM,yBAAyB,CAAC;AAC1E,OAAO,EAAE,uBAAuB,EAAE,MAAM,oBAAoB,CAAC;AAC7D,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,EAEL,gBAAgB,EAChB,yBAAyB,GAC1B,MAAM,kBAAkB,CAAC;AAoF1B,SAAS,4BAA4B,CACnC,KAAkB,EAClB,MAA4B;IAE5B,IAAI,CAAC,MAAM;QAAE,OAAO,IAAI,CAAC;IACzB,MAAM,QAA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nC,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC;QAC3B,CAAC;QACD,OAAO;YACL,MAAM,EAAE,IAAI;YACZ,QAAQ,EAAE,yBAAyB,CAAC,gBAAgB,CAAC;YACrD,WAAW,EAAE,CAAC,CAAC,CAAC,gBAAgB,IAAI,gBAAgB,CAAC,IAAI,EAAE,CAAC;SAC7D,CAAC;IACJ,CAAC;IAED,uEAAuE;IACvE,uEAAuE;IACvE,4DAA4D;IAC5D,IAAI,YAAY,CAAC,MAAM,GAAG,CAAC,IAAI,YAAY,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;QAC5D,OAAO;YACL,MAAM,EAAE,IAAI;YACZ,QAAQ,EAAE,yBAAyB,CAAC,gBAAgB,CAAC;YACrD,qDAAqD;YACrD,WAAW,EAAE,IAAI;SAClB,CAAC;IACJ,CAAC;IAED,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC;AAC3B,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,sBAAsB,CAC1C,SAA6B;IAE7B,IAAI,CAAC,SAAS;QAAE,OAAO,SAAS,CAAC;IACjC,IAAI,CAAC;QACH,MAAM,EAAE,kBAAkB,EAAE,GAAG,MAAM,MAAM,CAAC,mBAAmB,CAAC,CAAC;QACjE,MAAM,GAAG,GAAG,MAAM,kBAAkB,CAAC,SAAS,CAAC,CAAC;QAChD,OAAO,GAAG,EAAE,KAAK,IAAI,SAAS,CAAC;IACjC,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,SAAS,CAAC;IACnB,CAAC;AACH,CAAC","sourcesContent":["/**\n * Shared MCP server builder.\n *\n * Extracted from `server.ts` so the stateless Streamable-HTTP mount\n * (`mountMCP`) and the stdio transport (`runMCPStdio --standalone`) build the\n * *same* MCP server from the *same* `ActionEntry` registry. Both surfaces:\n *\n * - expose every action as an MCP tool (+ the `ask-agent` meta-tool),\n * - append the framework deep-link block / `_meta` to every tool result,\n * - wrap `run()` / `askAgent()` in `runWithRequestContext` so per-user /\n * per-org scoping (accessFilter, resolveCredential, MCP visibility) is\n * honoured.\n *\n * `server.ts` re-exports `createMCPServerForRequest` and the auth helpers so\n * any (future) external importer of `@agent-native/core/mcp` keeps resolving.\n *\n * Node-only at the SDK level, but this module itself has no Node-only imports\n * — it can be bundled into the serverless function alongside `mountMCP`.\n */\n\nimport type { ActionEntry } from \"../agent/production-agent.js\";\nimport { isMcpActionResult } from \"../mcp-client/app-result.js\";\nimport {\n MCP_APP_EXTENSION_ID,\n MCP_APP_MIME_TYPE,\n MCP_APP_RESOURCE_URI_META_KEY,\n type ActionMcpAppCsp,\n type ActionMcpAppResourceConfig,\n} from \"../action.js\";\nimport { MCP_APP_REQUEST_ORIGIN_CSP_SOURCE } from \"./embed-app.js\";\nimport { runWithRequestContext } from \"../server/request-context.js\";\nimport { toAbsoluteOpenUrl, toDesktopOpenUrl } from \"../server/deep-link.js\";\nimport {\n isAgentNativeOpenDeepLink,\n withCollapsedAgentSidebarParam,\n} from \"../shared/agent-sidebar-url.js\";\nimport { MCP_APP_CHAT_BRIDGE_QUERY_PARAM } from \"../shared/embed-auth.js\";\nimport { getBuiltinCrossAppTools } from \"./builtin-tools.js\";\nimport { MCP_CONNECT_SCOPE } from \"./connect-store.js\";\nimport {\n MCP_OAUTH_SCOPES,\n hasMcpOAuthScope,\n verifyMcpOAuthAccessToken,\n} from \"./oauth-token.js\";\n\nexport interface MCPConfig {\n /** App name shown in MCP server info */\n name: string;\n /**\n * Canonical app id (directory under `apps/`, e.g. `mail`) this MCP server\n * is mounted for. Optional & back-compat: when omitted the builtin\n * cross-app tools fall back to lowercasing `name`. Used by `open_app` /\n * `ask_app` / `create_workspace_app` to tell \"this app\" from a cross-app\n * target so they resolve the *target* app's origin rather than echoing the\n * current request origin.\n */\n appId?: string;\n /** App description */\n description: string;\n /** Version string (default \"1.0.0\") */\n version?: string;\n /** Action registry — same as agent chat and A2A */\n actions: Record<string, ActionEntry>;\n /**\n * Full (\"production\") action surface served to an **authenticated real\n * caller** — a connect-minted token, an `agent-native mcp install` stdio\n * proxy (owner-email header / `AGENT_NATIVE_OWNER_EMAIL`), or a deployed /\n * `AGENT_MODE=production` app. In local dev `actions` is intentionally the\n * sparse, dev-toggled surface (builtins + read-only public-agent actions)\n * so the local agent chat and unauthenticated dev probes don't see every\n * mutating tool; but per the external-agents contract a real caller that\n * connected with a token MUST get the full surface even in dev. When unset\n * (production, where `actions` already IS the full set) the swap is a\n * no-op. See `external-agents` skill, \"Dev vs production tool surface\".\n */\n productionActions?: Record<string, ActionEntry>;\n /** Handler for the ask-agent meta-tool — runs the full agent loop */\n askAgent?: (message: string) => Promise<string>;\n /**\n * Disable the generic cross-app builtin tools (`list_apps`, `open_app`,\n * `ask_app`, `create_workspace_app`, `list_templates`). They are merged in\n * by default so external agents get a stable verb set; a template action of\n * the same name always wins (template precedence). Set to `false` only for\n * a constrained / locked-down mount.\n */\n builtinCrossAppTools?: boolean;\n}\n\n/**\n * Identity extracted from a verified MCP bearer token / JWT. Used to wrap\n * `entry.run()` and `config.askAgent()` calls in `runWithRequestContext`\n * so downstream tools (db-query, accessFilter, resolveCredential) honour\n * per-user / per-org scoping. Without this wrap the MCP endpoint would\n * silently bypass tenant isolation. See finding #6 in\n * /tmp/security-audit/12-mcp-a2a-agent.md.\n */\nexport interface MCPCallerIdentity {\n userEmail: string | undefined;\n orgDomain: string | undefined;\n /** Present only for standard remote MCP OAuth access tokens. */\n oauthScopes?: string[];\n /** Present only for standard remote MCP OAuth access tokens. */\n oauthClientId?: string;\n}\n\n/** Per-request context used to turn an action's relative deep link into the\n * absolute web URL (and desktop `agentnative://` URL) the external agent\n * surfaces. Derived from the inbound request headers in `mountMCP`, or from\n * the resolved local app origin in the stdio standalone path. */\nexport interface MCPRequestMeta {\n /** Origin of the running app, e.g. `http://localhost:8100`. */\n origin?: string;\n /** Optional client preference for which URL the *markdown* link uses. */\n target?: \"browser\" | \"desktop\" | \"terminal\";\n /**\n * The caller authenticated with a real credential (verified A2A/connect\n * JWT, matching ACCESS_TOKEN, or a forwarded owner-email header from\n * `agent-native mcp install`) — not the unauthenticated local dev-open\n * path. When true, `createMCPServerForRequest` serves\n * `config.productionActions` (the full surface) instead of the sparse dev\n * `config.actions`. Set by `mountMCP` from `verifyAuth`.\n */\n fullSurface?: boolean;\n}\n\ntype McpOAuthScope = (typeof MCP_OAUTH_SCOPES)[number];\n\nfunction isActionVisibleForOAuthScope(\n entry: ActionEntry,\n scopes: string[] | undefined,\n): boolean {\n if (!scopes) return true;\n const required: McpOAuthScope =\n entry.readOnly === true ? \"mcp:read\" : \"mcp:write\";\n return hasMcpOAuthScope(scopes, required);\n}\n\nconst COMPACT_MCP_APP_CATALOG_BUILTINS = new Set([\n \"list_apps\",\n \"open_app\",\n \"ask_app\",\n \"create_embed_session\",\n]);\n\nfunction isActionAdvertisedInCompactMcpAppCatalog(\n config: MCPConfig,\n name: string,\n entry: ActionEntry,\n): boolean {\n if (COMPACT_MCP_APP_CATALOG_BUILTINS.has(name)) return true;\n if (\n (entry.mcpApp as { compactCatalog?: unknown } | undefined)\n ?.compactCatalog === true\n ) {\n return true;\n }\n // If an app deliberately disables the generic open_app builtin, fall back to\n // its action-specific MCP App tools so it still has a UI surface. The normal\n // default is the opposite: keep chat-host catalogs tiny and route UI via\n // open_app instead of listing every app action/template.\n if (config.builtinCrossAppTools === false) {\n return Boolean(entry.mcpApp?.resource);\n }\n return false;\n}\n\nconst MCP_APP_OAUTH_CLIENT_RE = /\\b(chatgpt|openai|claude|anthropic)\\b/i;\nconst NON_APP_OAUTH_CLIENT_RE =\n /\\b(code|desktop|cli|cursor|codex|goose|postman|mcpjam|inspector)\\b/i;\nconst MCP_APP_OAUTH_REDIRECT_HOST_RE =\n /(^|\\.)((chatgpt|openai)\\.com|claude\\.ai|anthropic\\.com)$/i;\n\nasync function isKnownMcpAppOAuthClient(\n identity: MCPCallerIdentity | undefined,\n): Promise<boolean> {\n const clientId = identity?.oauthClientId?.trim();\n if (!clientId) return false;\n\n function isKnownAppClientName(value: string | undefined | null): boolean {\n if (!value) return false;\n return (\n MCP_APP_OAUTH_CLIENT_RE.test(value) &&\n !NON_APP_OAUTH_CLIENT_RE.test(value)\n );\n }\n\n function isKnownNonAppClientName(value: string | undefined | null): boolean {\n return Boolean(value && NON_APP_OAUTH_CLIENT_RE.test(value));\n }\n\n function isKnownMcpAppRedirectUri(uri: string): boolean {\n try {\n const url = new URL(uri);\n return (\n url.protocol === \"https:\" &&\n MCP_APP_OAUTH_REDIRECT_HOST_RE.test(url.hostname)\n );\n } catch {\n return false;\n }\n }\n\n if (isKnownAppClientName(clientId)) return true;\n if (isKnownNonAppClientName(clientId)) return false;\n\n try {\n const { getOAuthClient } = await import(\"./oauth-store.js\");\n const client = await getOAuthClient(clientId);\n // If the token carries an OAuth client id but its registration is missing,\n // keep the model on the compact MCP Apps surface instead of exposing every\n // private action/schema.\n if (!client) return true;\n if (isKnownAppClientName(client.clientName)) return true;\n if (isKnownNonAppClientName(client.clientName)) return false;\n if (client.redirectUris.some(isKnownMcpAppRedirectUri)) return true;\n // Most OAuth hosts are UI-oriented MCP clients. Preserve the full catalog\n // only for known code/CLI clients so unknown browser hosts cannot trigger\n // massive resources/list payloads.\n return true;\n } catch {\n // On metadata lookup errors, fail compact instead of falling back to the\n // full action surface; ChatGPT/Claude old tokens otherwise get huge lists.\n return true;\n }\n}\n\ninterface ResolvedMcpAppResource {\n uri: string;\n legacyUris?: string[];\n name: string;\n title?: string;\n description?: string;\n html: ActionMcpAppResourceConfig[\"html\"];\n mimeType: typeof MCP_APP_MIME_TYPE;\n _meta?: Record<string, unknown>;\n}\n\ninterface McpAppResourceContext {\n actionName: string;\n appId?: string;\n requestOrigin?: string;\n}\n\ninterface VersionedMcpAppResourceUri {\n uri: string;\n legacyUris?: string[];\n}\n\nfunction metadataObject(value: unknown): Record<string, unknown> {\n return value && typeof value === \"object\" && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : {};\n}\n\nfunction originString(value: unknown): string | undefined {\n if (typeof value !== \"string\" || !value.trim()) return undefined;\n try {\n return new URL(value).origin;\n } catch {\n return undefined;\n }\n}\n\nfunction withMcpChatBridgeParam(urlOrPath: string): string {\n try {\n const base = \"http://agent-native.invalid\";\n const url = urlOrPath.startsWith(\"/\")\n ? new URL(urlOrPath, base)\n : new URL(urlOrPath);\n url.searchParams.set(MCP_APP_CHAT_BRIDGE_QUERY_PARAM, \"1\");\n return urlOrPath.startsWith(\"/\")\n ? `${url.pathname}${url.search}${url.hash}`\n : url.toString();\n } catch {\n return urlOrPath;\n }\n}\n\nfunction mcpAppEmbedOpenLinkMeta(\n result: unknown,\n resource: ResolvedMcpAppResource,\n meta: MCPRequestMeta | undefined,\n): Record<string, unknown> {\n const out = metadataObject(result);\n const embedStartUrl =\n typeof out.embedStartUrl === \"string\"\n ? out.embedStartUrl\n : out.embed === true &&\n typeof out.url === \"string\" &&\n out.url.includes(\"/_agent-native/embed/start\")\n ? out.url\n : null;\n if (!embedStartUrl) return {};\n\n const webUrl = toAbsoluteOpenUrl(\n withMcpChatBridgeParam(embedStartUrl),\n meta?.origin,\n );\n const deepLinkUrl =\n typeof out.deepLinkUrl === \"string\" ? out.deepLinkUrl : null;\n const fallbackLabel = resource.title ?? resource.name ?? \"app\";\n const label =\n typeof out.app === \"string\" && out.app.trim()\n ? `Open ${out.app.trim()}`\n : fallbackLabel;\n const view =\n typeof out.view === \"string\" && out.view.trim()\n ? out.view.trim()\n : typeof out.path === \"string\" && out.path.trim()\n ? out.path.trim()\n : undefined;\n\n return {\n \"agent-native/openLink\": {\n label,\n ...(view ? { view } : {}),\n webUrl,\n desktopUrl: deepLinkUrl\n ? toAbsoluteOpenUrl(deepLinkUrl, meta?.origin)\n : webUrl,\n },\n };\n}\n\n/**\n * Build the deep-link content block + structured `_meta` for a tool result.\n * Best-effort: any throw / nullish link is swallowed so a bad `link` builder\n * never fails the tool call.\n */\nexport function buildLinkArtifacts(\n entry: ActionEntry,\n args: Record<string, any>,\n result: any,\n meta: MCPRequestMeta | undefined,\n): {\n block?: { type: \"text\"; text: string };\n _meta?: Record<string, unknown>;\n} {\n if (typeof entry.link !== \"function\") return {};\n try {\n const lk = entry.link({ args: args ?? {}, result });\n if (!lk?.url) return {};\n const linkUrl = isAgentNativeOpenDeepLink(lk.url)\n ? withCollapsedAgentSidebarParam(lk.url)\n : lk.url;\n const webUrl = toAbsoluteOpenUrl(linkUrl, meta?.origin);\n const desktopUrl = toDesktopOpenUrl(linkUrl);\n const markdownUrl = meta?.target === \"desktop\" ? desktopUrl : webUrl;\n return {\n block: { type: \"text\", text: `\\n\\n[${lk.label} →](${markdownUrl})` },\n _meta: {\n \"agent-native/openLink\": {\n label: lk.label,\n view: lk.view,\n webUrl,\n desktopUrl,\n },\n },\n };\n } catch {\n return {};\n }\n}\n\n/**\n * Merge the generic cross-app builtin tools into the config's action\n * registry. **Template actions take precedence**: if a template defines an\n * action with the same name as a builtin (e.g. its own `list_apps`), the\n * template entry wins and the builtin is dropped. This mirrors the\n * template-over-workspace-core precedence in `autoDiscoverActions`.\n *\n * The builtins are pure-ish navigators / scaffolders; they call back into the\n * same `config.actions` / `config.askAgent` so there is no second agent loop.\n */\nfunction mergeBuiltinTools(\n config: MCPConfig,\n baseActions: Record<string, ActionEntry>,\n requestMeta?: MCPRequestMeta,\n): Record<string, ActionEntry> {\n if (config.builtinCrossAppTools === false) return baseActions;\n const builtins = getBuiltinCrossAppTools(config, requestMeta);\n const merged: Record<string, ActionEntry> = { ...builtins };\n // Template / app actions overwrite same-named builtins.\n for (const [name, entry] of Object.entries(baseActions)) {\n merged[name] = entry;\n }\n return merged;\n}\n\nfunction safeUiSegment(value: string | undefined, fallback: string): string {\n const normalized = (value || fallback)\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9._-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n return normalized || fallback;\n}\n\n// ChatGPT and Claude cache MCP App resource HTML by `ui://` URI. Bump this\n// when the shared shell changes in a way that must invalidate host caches.\nconst MCP_APP_RESOURCE_SHELL_VERSION = \"shell-v25\";\n\nfunction legacyDefaultMcpAppUri(config: MCPConfig, actionName: string): string {\n const app = safeUiSegment(config.appId ?? config.name, \"agent-native\");\n const action = safeUiSegment(actionName, \"tool\");\n return `ui://${app}/${action}`;\n}\n\nfunction versionMcpAppResourceUri(\n rawUri: string,\n): VersionedMcpAppResourceUri | null {\n const uri = rawUri.trim();\n if (!uri.startsWith(\"ui://\")) return null;\n const versionSuffix = `/${MCP_APP_RESOURCE_SHELL_VERSION}`;\n let versionedUri: string;\n try {\n const parsed = new URL(uri);\n const path = parsed.pathname.replace(/\\/+$/g, \"\");\n parsed.pathname = /\\/shell-v\\d+$/.test(path)\n ? path.replace(/\\/shell-v\\d+$/, versionSuffix)\n : `${path}${versionSuffix}`;\n versionedUri = parsed.toString();\n } catch {\n return null;\n }\n return {\n uri: versionedUri,\n ...(versionedUri !== uri ? { legacyUris: [uri] } : {}),\n };\n}\n\nfunction getMcpAppResourceUri(\n config: MCPConfig,\n actionName: string,\n entry: ActionEntry,\n): VersionedMcpAppResourceUri | null {\n const resource = entry.mcpApp?.resource;\n if (!resource) return null;\n const baseUri =\n resource.uri?.trim() || legacyDefaultMcpAppUri(config, actionName);\n return versionMcpAppResourceUri(baseUri);\n}\n\nfunction expandRequestOriginSources(\n sources: string[] | undefined,\n requestMeta?: MCPRequestMeta,\n): string[] | undefined {\n if (!sources) return undefined;\n const origin = requestMeta?.origin;\n return sources.flatMap((source) =>\n source === MCP_APP_REQUEST_ORIGIN_CSP_SOURCE && origin\n ? [origin]\n : [source],\n );\n}\n\nfunction openAiWidgetCsp(\n cspConfig: ActionMcpAppCsp | undefined,\n requestMeta?: MCPRequestMeta,\n): Record<string, string[]> | undefined {\n if (!cspConfig) return undefined;\n const csp: Record<string, string[]> = {};\n const connectDomains = expandRequestOriginSources(\n cspConfig.connectDomains,\n requestMeta,\n );\n const resourceDomains = expandRequestOriginSources(\n cspConfig.resourceDomains,\n requestMeta,\n );\n const frameDomains = expandRequestOriginSources(\n cspConfig.frameDomains,\n requestMeta,\n );\n if (connectDomains?.length) csp.connect_domains = connectDomains;\n if (resourceDomains?.length) csp.resource_domains = resourceDomains;\n if (frameDomains?.length) csp.frame_domains = frameDomains;\n return Object.keys(csp).length > 0 ? csp : undefined;\n}\n\nfunction mcpAppUiMeta(\n resource: ActionMcpAppResourceConfig,\n resolvedCsp: ActionMcpAppCsp | undefined,\n requestMeta?: MCPRequestMeta,\n description?: string,\n): Record<string, unknown> | undefined {\n const base =\n resource._meta && typeof resource._meta === \"object\"\n ? { ...resource._meta }\n : {};\n const existingUi =\n base.ui && typeof base.ui === \"object\" && !Array.isArray(base.ui)\n ? (base.ui as Record<string, unknown>)\n : {};\n const ui: Record<string, unknown> = { ...existingUi };\n if (resolvedCsp) {\n ui.csp = {\n ...resolvedCsp,\n connectDomains: expandRequestOriginSources(\n resolvedCsp.connectDomains,\n requestMeta,\n ),\n resourceDomains: expandRequestOriginSources(\n resolvedCsp.resourceDomains,\n requestMeta,\n ),\n frameDomains: expandRequestOriginSources(\n resolvedCsp.frameDomains,\n requestMeta,\n ),\n baseUriDomains: expandRequestOriginSources(\n resolvedCsp.baseUriDomains,\n requestMeta,\n ),\n };\n }\n if (resource.permissions) ui.permissions = resource.permissions;\n const widgetDomain =\n originString(resource.domain) ??\n originString(ui.domain) ??\n originString(requestMeta?.origin);\n if (widgetDomain) ui.domain = widgetDomain;\n if (typeof resource.prefersBorder === \"boolean\") {\n ui.prefersBorder = resource.prefersBorder;\n }\n if (Object.keys(ui).length > 0) base.ui = ui;\n if (description && base[\"openai/widgetDescription\"] == null) {\n base[\"openai/widgetDescription\"] = description;\n }\n if (\n typeof resource.prefersBorder === \"boolean\" &&\n base[\"openai/widgetPrefersBorder\"] == null\n ) {\n base[\"openai/widgetPrefersBorder\"] = resource.prefersBorder;\n }\n const openAiCsp = openAiWidgetCsp(resolvedCsp, requestMeta);\n if (openAiCsp && base[\"openai/widgetCSP\"] == null) {\n base[\"openai/widgetCSP\"] = openAiCsp;\n }\n if (widgetDomain && base[\"openai/widgetDomain\"] == null) {\n base[\"openai/widgetDomain\"] = widgetDomain;\n }\n return Object.keys(base).length > 0 ? base : undefined;\n}\n\nasync function resolveMcpAppCsp(\n resource: ActionMcpAppResourceConfig,\n ctx: McpAppResourceContext,\n): Promise<ActionMcpAppCsp | undefined> {\n if (!resource.csp) return undefined;\n return typeof resource.csp === \"function\"\n ? await resource.csp(ctx)\n : resource.csp;\n}\n\nasync function resolveMcpAppResource(\n config: MCPConfig,\n actionName: string,\n entry: ActionEntry,\n requestMeta?: MCPRequestMeta,\n): Promise<ResolvedMcpAppResource | null> {\n const resource = entry.mcpApp?.resource;\n if (!resource) return null;\n const resolvedUri = getMcpAppResourceUri(config, actionName, entry);\n if (!resolvedUri) return null;\n const description = resource.description ?? entry.tool.description;\n const resolvedCsp = await resolveMcpAppCsp(resource, {\n actionName,\n appId: config.appId,\n requestOrigin: requestMeta?.origin,\n });\n const resourceMeta = mcpAppUiMeta(\n resource,\n resolvedCsp,\n requestMeta,\n description,\n );\n return {\n uri: resolvedUri.uri,\n ...(resolvedUri.legacyUris ? { legacyUris: resolvedUri.legacyUris } : {}),\n name: resource.name?.trim() || actionName,\n ...(resource.title ? { title: resource.title } : {}),\n ...(description ? { description } : {}),\n html: resource.html,\n mimeType: resource.mimeType ?? MCP_APP_MIME_TYPE,\n ...(resourceMeta ? { _meta: resourceMeta } : {}),\n };\n}\n\nasync function resolveMcpAppResourceSafely(\n config: MCPConfig,\n actionName: string,\n entry: ActionEntry,\n requestMeta?: MCPRequestMeta,\n): Promise<ResolvedMcpAppResource | null> {\n try {\n return await resolveMcpAppResource(config, actionName, entry, requestMeta);\n } catch (error) {\n console.warn(\n `[mcp] Skipping MCP App resource for action \"${actionName}\" because its metadata could not be resolved.`,\n error,\n );\n return null;\n }\n}\n\nasync function getMcpAppResources(\n config: MCPConfig,\n actions: Record<string, ActionEntry>,\n requestMeta?: MCPRequestMeta,\n): Promise<ResolvedMcpAppResource[]> {\n const resources = await Promise.all(\n Object.entries(actions).map(([name, entry]) =>\n resolveMcpAppResourceSafely(config, name, entry, requestMeta),\n ),\n );\n return resources.filter((resource): resource is ResolvedMcpAppResource =>\n Boolean(resource),\n );\n}\n\nfunction renderMcpAppHtml(\n resource: ResolvedMcpAppResource,\n actionName: string,\n config: MCPConfig,\n requestMeta?: MCPRequestMeta,\n): string {\n if (typeof resource.html === \"function\") {\n return resource.html({\n actionName,\n appId: config.appId,\n requestOrigin: requestMeta?.origin,\n });\n }\n return resource.html;\n}\n\nfunction openAiToolDescriptorMeta(\n resource: ResolvedMcpAppResource,\n): Record<string, unknown> {\n const label = resource.title ?? resource.name;\n const widgetCsp = metadataObject(resource._meta?.[\"openai/widgetCSP\"]);\n return {\n \"openai/outputTemplate\": resource.uri,\n \"openai/toolInvocation/invoking\": `Opening ${label}`,\n \"openai/toolInvocation/invoked\": `${label} ready`,\n \"openai/widgetAccessible\": true,\n ...(Object.keys(widgetCsp).length > 0\n ? { \"openai/widgetCSP\": widgetCsp }\n : {}),\n };\n}\n\nfunction openAiToolResultMeta(\n resource: ResolvedMcpAppResource,\n): Record<string, unknown> {\n const label = resource.title ?? resource.name;\n const widgetCsp = metadataObject(resource._meta?.[\"openai/widgetCSP\"]);\n return {\n \"openai/outputTemplate\": resource.uri,\n \"openai/toolInvocation/invoking\": `Opening ${label}`,\n \"openai/toolInvocation/invoked\": `${label} ready`,\n \"openai/widgetAccessible\": true,\n ...(Object.keys(widgetCsp).length > 0\n ? { \"openai/widgetCSP\": widgetCsp }\n : {}),\n };\n}\n\nfunction mcpAppToolUiMeta(\n resource: ResolvedMcpAppResource,\n visibility: unknown,\n): Record<string, unknown> {\n return {\n resourceUri: resource.uri,\n visibility: Array.isArray(visibility) ? visibility : [\"model\", \"app\"],\n };\n}\n\nfunction primitiveValue(value: unknown): value is string | number | boolean {\n return (\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\"\n );\n}\n\nfunction mcpAppStructuredContent(\n result: unknown,\n meta: Record<string, unknown> | undefined,\n): Record<string, unknown> {\n const out: Record<string, unknown> =\n result && typeof result === \"object\" && !Array.isArray(result)\n ? { ...(result as Record<string, unknown>) }\n : primitiveValue(result)\n ? { result }\n : {};\n const openLink = meta?.[\"agent-native/openLink\"];\n if (openLink && typeof openLink === \"object\" && !Array.isArray(openLink)) {\n out.openLink = openLink;\n const webUrl = (openLink as Record<string, unknown>).webUrl;\n if (typeof webUrl === \"string\" && !out.url) out.url = webUrl;\n }\n return Object.keys(out).length > 0 ? out : { status: \"ok\" };\n}\n\nfunction truncateToolText(value: string, max = 2000): string {\n if (value.length <= max) return value;\n return `${value.slice(0, max - 1)}…`;\n}\n\nfunction conciseMcpAppToolText(\n name: string,\n result: unknown,\n structuredContent: Record<string, unknown>,\n): string {\n if (typeof result === \"string\") return truncateToolText(result);\n const message = structuredContent.message;\n if (typeof message === \"string\" && message.trim()) {\n return truncateToolText(message.trim());\n }\n const title = structuredContent.title ?? structuredContent.name;\n if (typeof title === \"string\" && title.trim()) {\n return `${title.trim()} is ready.`;\n }\n const id = structuredContent.id;\n if (typeof id === \"string\" && id.trim()) {\n return `${name} completed for ${id.trim()}.`;\n }\n return `${name} completed.`;\n}\n\n// ---------------------------------------------------------------------------\n// MCP Server creation — converts ActionEntry registry to MCP tools\n// ---------------------------------------------------------------------------\n\n/**\n * Build a fully-wired MCP `Server` for a single request / session.\n *\n * Shared by the stateless Streamable-HTTP mount (`mountMCP`) and the stdio\n * standalone transport. The HTTP mount passes the per-request origin via\n * `requestMeta`; the stdio standalone path passes the resolved local app\n * origin so deep links still become absolute URLs.\n */\nexport async function createMCPServerForRequest(\n config: MCPConfig,\n identity: MCPCallerIdentity | undefined,\n requestMeta?: MCPRequestMeta,\n) {\n const { Server } = await import(\"@modelcontextprotocol/sdk/server/index.js\");\n const {\n ListToolsRequestSchema,\n CallToolRequestSchema,\n ListResourcesRequestSchema,\n ReadResourceRequestSchema,\n ListResourceTemplatesRequestSchema,\n } = await import(\"@modelcontextprotocol/sdk/types.js\");\n\n // Resolve the effective caller identity. JWT / header-derived identity\n // (passed by `mountMCP` via `verifyAuth`) wins. When the caller passed no\n // identity — the stdio **standalone** path — fall back to the\n // `AGENT_NATIVE_OWNER_EMAIL` env the `agent-native mcp install` flow writes\n // into the `agent-native mcp serve` process env, so standalone tool runs are\n // tenant-scoped to the configured owner instead of running unscoped. Stays\n // undefined for true dev-open (no token, no secret, no owner) — behavior\n // there is unchanged.\n const ownerFromEnv = process.env.AGENT_NATIVE_OWNER_EMAIL?.trim();\n const effectiveIdentity: MCPCallerIdentity | undefined =\n identity ??\n (ownerFromEnv\n ? { userEmail: ownerFromEnv, orgDomain: undefined }\n : undefined);\n\n // The action set the request handlers operate on = base actions + generic\n // cross-app builtins (template wins on name collision). An authenticated\n // real caller (connect-minted token / `mcp install` owner / production —\n // `requestMeta.fullSurface`, or the stdio standalone path identified by\n // `AGENT_NATIVE_OWNER_EMAIL`) gets the full `productionActions` surface\n // even in local dev; the unauthenticated dev-open path keeps the sparse\n // `config.actions`. See `external-agents` skill, \"Dev vs production tool\n // surface\".\n const useFullSurface = requestMeta?.fullSurface === true || !!ownerFromEnv;\n const baseActions =\n useFullSurface && config.productionActions\n ? config.productionActions\n : config.actions;\n const actions = mergeBuiltinTools(config, baseActions, requestMeta);\n const visibleActions = Object.fromEntries(\n Object.entries(actions).filter(([, entry]) =>\n isActionVisibleForOAuthScope(entry, effectiveIdentity?.oauthScopes),\n ),\n );\n const compactMcpAppCatalog =\n (Array.isArray(effectiveIdentity?.oauthScopes) &&\n hasMcpOAuthScope(effectiveIdentity.oauthScopes, \"mcp:apps\")) ||\n (await isKnownMcpAppOAuthClient(effectiveIdentity));\n const advertisedActions = compactMcpAppCatalog\n ? Object.fromEntries(\n Object.entries(visibleActions).filter(([name, entry]) =>\n isActionAdvertisedInCompactMcpAppCatalog(config, name, entry),\n ),\n )\n : visibleActions;\n const supportsMcpApps =\n compactMcpAppCatalog &&\n Object.values(advertisedActions).some((entry) =>\n Boolean(entry.mcpApp?.resource),\n );\n const server = new Server(\n { name: config.name, version: config.version ?? \"1.0.0\" },\n {\n capabilities: {\n tools: {},\n ...(supportsMcpApps\n ? {\n resources: {},\n extensions: {\n [MCP_APP_EXTENSION_ID]: {\n mimeTypes: [MCP_APP_MIME_TYPE],\n },\n },\n }\n : {}),\n },\n },\n );\n\n // Resolve orgId once per request (DB lookup) so subsequent wraps are\n // synchronous. The caller identity may be undefined for true dev-open —\n // in that case we run with no userEmail/orgId, which makes downstream\n // tools that require per-user scope return empty results rather than\n // cross-tenant data (the safe default).\n const orgIdPromise = resolveOrgIdFromDomain(effectiveIdentity?.orgDomain);\n\n /**\n * Wrap a callback in\n * `runWithRequestContext({ userEmail, orgId, requestOrigin }, fn)`.\n * Both the tools/list and tools/call handlers go through this so\n * downstream `accessFilter`, `resolveCredential`, and per-user MCP\n * visibility checks see the verified caller's identity. `requestOrigin`\n * is the live server origin derived from the inbound request (same value\n * used to absolutize deep links) so actions that build fetchable URLs\n * (e.g. design `export-coding-handoff`'s signed raw-code URL) resolve the\n * correct local-workspace origin instead of a prod/localhost fallback.\n */\n async function withCallerContext<T>(fn: () => Promise<T>): Promise<T> {\n const orgId = await orgIdPromise;\n return runWithRequestContext(\n {\n userEmail: effectiveIdentity?.userEmail,\n orgId,\n ...(requestMeta?.origin ? { requestOrigin: requestMeta.origin } : {}),\n },\n fn,\n ) as Promise<T>;\n }\n\n // tools/list — return all actions + ask-agent meta-tool. Wrapped in the\n // request context so per-user MCP visibility (mcp-client/visibility.ts)\n // applies to the listing too.\n server.setRequestHandler(ListToolsRequestSchema, async () => {\n return withCallerContext(async () => {\n const tools = await Promise.all(\n Object.entries(advertisedActions).map(async ([name, entry]) => {\n const hasLink = typeof entry.link === \"function\";\n const mcpAppResource = await resolveMcpAppResourceSafely(\n config,\n name,\n entry,\n requestMeta,\n );\n const rawToolMeta =\n (entry.tool as any)._meta &&\n typeof (entry.tool as any)._meta === \"object\" &&\n !Array.isArray((entry.tool as any)._meta)\n ? { ...((entry.tool as any)._meta as Record<string, unknown>) }\n : {};\n const toolMeta = {\n ...rawToolMeta,\n ...(mcpAppResource\n ? {\n ...openAiToolDescriptorMeta(mcpAppResource),\n [MCP_APP_RESOURCE_URI_META_KEY]: mcpAppResource.uri,\n ui: mcpAppToolUiMeta(\n mcpAppResource,\n entry.mcpApp?.visibility ??\n metadataObject(rawToolMeta.ui).visibility,\n ),\n }\n : {}),\n };\n const baseDescription = entry.tool.description ?? name;\n const annotations: Record<string, unknown> = {\n readOnlyHint: entry.readOnly === true,\n destructiveHint: entry.publicAgent?.isConsequential === true,\n openWorldHint: false,\n };\n if (hasLink) annotations[\"agent-native/producesOpenLink\"] = true;\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 ...(Object.keys(toolMeta).length > 0 ? { _meta: toolMeta } : {}),\n annotations,\n };\n }),\n );\n\n if (\n !compactMcpAppCatalog &&\n config.askAgent &&\n hasMcpOAuthScope(effectiveIdentity?.oauthScopes, \"mcp:write\")\n ) {\n tools.push({\n name: \"ask-agent\",\n description:\n \"Send a natural-language message to the app's AI agent and get a response. \" +\n \"Use this for complex, multi-step tasks that require the agent's reasoning \" +\n \"and full context about the app.\",\n inputSchema: {\n type: \"object\" as const,\n properties: {\n message: {\n type: \"string\",\n description: \"The message to send to the agent\",\n },\n },\n required: [\"message\"],\n },\n annotations: {\n readOnlyHint: false,\n destructiveHint: false,\n openWorldHint: false,\n },\n });\n }\n\n return { tools };\n });\n });\n\n // tools/call — dispatch to action registry or ask-agent. Wrapped in the\n // request context so the action's `run(args)` and `askAgent()` execute\n // with the verified caller's identity, not the platform default.\n server.setRequestHandler(CallToolRequestSchema, async (request: any) => {\n return withCallerContext(async () => {\n const { name, arguments: args } = request.params;\n\n if (name === \"ask-agent\" && config.askAgent) {\n if (compactMcpAppCatalog) {\n return {\n content: [{ type: \"text\", text: `Unknown tool: ${name}` }],\n isError: true,\n };\n }\n if (!hasMcpOAuthScope(effectiveIdentity?.oauthScopes, \"mcp:write\")) {\n return {\n content: [\n {\n type: \"text\",\n text: \"Forbidden: OAuth scope does not allow ask-agent\",\n },\n ],\n isError: true,\n };\n }\n const message = args?.message ?? \"\";\n try {\n const result = await config.askAgent(message);\n return { content: [{ type: \"text\", text: result }] };\n } catch (err: any) {\n return {\n content: [{ type: \"text\", text: `Error: ${err.message}` }],\n isError: true,\n };\n }\n }\n\n const callableActions = compactMcpAppCatalog\n ? advertisedActions\n : actions;\n const entry = callableActions[name];\n if (!entry) {\n return {\n content: [{ type: \"text\", text: `Unknown tool: ${name}` }],\n isError: true,\n };\n }\n if (\n !isActionVisibleForOAuthScope(entry, effectiveIdentity?.oauthScopes)\n ) {\n return {\n content: [\n {\n type: \"text\",\n text: `Forbidden: OAuth scope does not allow tool ${name}`,\n },\n ],\n isError: true,\n };\n }\n\n try {\n const result = await entry.run((args as Record<string, string>) ?? {});\n const rawResult = isMcpActionResult(result) ? result.raw : result;\n const resultForClient = isMcpActionResult(result)\n ? result.text\n : result;\n const mcpAppResource = await resolveMcpAppResourceSafely(\n config,\n name,\n entry,\n requestMeta,\n );\n const { block, _meta } = buildLinkArtifacts(\n entry,\n (args as Record<string, any>) ?? {},\n rawResult,\n requestMeta,\n );\n const responseMeta: Record<string, unknown> = {\n ...(_meta ?? {}),\n ...(mcpAppResource\n ? mcpAppEmbedOpenLinkMeta(rawResult, mcpAppResource, requestMeta)\n : {}),\n ...(mcpAppResource ? openAiToolResultMeta(mcpAppResource) : {}),\n };\n const structuredContent = mcpAppResource\n ? mcpAppStructuredContent(rawResult, responseMeta)\n : undefined;\n const text = mcpAppResource\n ? conciseMcpAppToolText(name, resultForClient, structuredContent!)\n : typeof resultForClient === \"string\"\n ? resultForClient\n : JSON.stringify(resultForClient);\n const content: any[] = [{ type: \"text\", text }];\n if (block) content.push(block);\n return {\n content,\n ...(structuredContent ? { structuredContent } : {}),\n ...(Object.keys(responseMeta).length > 0\n ? { _meta: responseMeta }\n : {}),\n };\n } catch (err: any) {\n return {\n content: [{ type: \"text\", text: `Error: ${err.message}` }],\n isError: true,\n };\n }\n });\n });\n\n if (supportsMcpApps) {\n server.setRequestHandler(ListResourcesRequestSchema, async () => {\n return withCallerContext(async () => {\n const mcpAppResources = await getMcpAppResources(\n config,\n advertisedActions,\n requestMeta,\n );\n return {\n resources: mcpAppResources.map((resource) => ({\n uri: resource.uri,\n name: resource.name,\n ...(resource.title ? { title: resource.title } : {}),\n ...(resource.description\n ? { description: resource.description }\n : {}),\n mimeType: resource.mimeType,\n ...(resource._meta ? { _meta: resource._meta } : {}),\n })),\n };\n });\n });\n\n server.setRequestHandler(ListResourceTemplatesRequestSchema, async () => {\n return withCallerContext(async () => {\n const mcpAppResources = await getMcpAppResources(\n config,\n advertisedActions,\n requestMeta,\n );\n return {\n resourceTemplates: mcpAppResources.map((resource) => ({\n uriTemplate: resource.uri,\n name: resource.name,\n ...(resource.title ? { title: resource.title } : {}),\n ...(resource.description\n ? { description: resource.description }\n : {}),\n mimeType: resource.mimeType,\n ...(resource._meta ? { _meta: resource._meta } : {}),\n })),\n };\n });\n });\n\n server.setRequestHandler(\n ReadResourceRequestSchema,\n async (request: any) => {\n return withCallerContext(async () => {\n const uri = request.params?.uri;\n let found: {\n actionName: string;\n resource: ResolvedMcpAppResource;\n } | null = null;\n for (const [name, entry] of Object.entries(advertisedActions)) {\n const resourceUri = getMcpAppResourceUri(config, name, entry);\n if (\n !resourceUri ||\n (resourceUri.uri !== uri &&\n !resourceUri.legacyUris?.includes(uri))\n ) {\n continue;\n }\n const resource = await resolveMcpAppResourceSafely(\n config,\n name,\n entry,\n requestMeta,\n );\n if (resource) {\n found = { actionName: name, resource };\n }\n break;\n }\n if (!found) {\n throw new Error(`MCP App resource not found: ${uri}`);\n }\n return {\n contents: [\n {\n uri,\n mimeType: found.resource.mimeType,\n text: renderMcpAppHtml(\n found.resource,\n found.actionName,\n config,\n requestMeta,\n ),\n ...(found.resource._meta\n ? { _meta: found.resource._meta }\n : {}),\n },\n ],\n };\n });\n },\n );\n }\n\n return server;\n}\n\n// ---------------------------------------------------------------------------\n// Auth — reuses the same pattern as A2A (Bearer token or JWT). Shared so the\n// HTTP mount and any stdio-side auth-aware helper resolve identity identically.\n// ---------------------------------------------------------------------------\n\nexport function getAccessTokens(): string[] {\n const single = process.env.ACCESS_TOKEN;\n const multi = process.env.ACCESS_TOKENS;\n const tokens: string[] = [];\n if (single) tokens.push(single);\n if (multi) {\n tokens.push(\n ...multi\n .split(\",\")\n .map((t) => t.trim())\n .filter(Boolean),\n );\n }\n return tokens;\n}\n\n/**\n * Resolve the caller identity for a static-token (or dev-open) auth path.\n *\n * Static `ACCESS_TOKEN` / `ACCESS_TOKENS` auth carries no per-caller claims,\n * so without this the MCP endpoint would run every tool with\n * `userEmail === undefined` and per-user / per-org scoped actions\n * (`accessFilter`, `resolveAccess`, `resolveCredential`) would return\n * empty / wrong data. The `agent-native mcp install` flow writes\n * `AGENT_NATIVE_OWNER_EMAIL` into the client config env and the stdio proxy\n * forwards it as the `X-Agent-Native-Owner-Email` request header (see\n * `mcp/stdio.ts#authHeaders`). We trust that owner hint *only* on the\n * static-token path — JWT auth already carries a cryptographically verified\n * `sub`, so the header is ignored there and never widens JWT scope.\n *\n * Precedence is server-trusted-first: the server process's\n * `AGENT_NATIVE_OWNER_EMAIL` env (set out-of-band by the operator / deploy)\n * ALWAYS wins, and a client-supplied `X-Agent-Native-Owner-Email` header is\n * honored *only as a fallback when that env is unset*. A static `ACCESS_TOKEN`\n * is a shared bearer secret; letting a request header override a\n * server-configured owner would let anyone holding a leaked token act as any\n * user. The header path remains for the single-tenant local-dev install flow\n * where the app server process has no owner env and the token *is* the\n * workspace secret; multi-tenant deployments must use A2A JWT (verified `sub`),\n * not a static token, for per-user scope.\n *\n * Returns `undefined` when no owner email is available (true dev-open: no\n * token, no secret, no owner) so behavior there stays unchanged.\n */\nfunction deriveStaticTokenIdentity(\n ownerEmailHeader: string | undefined,\n): MCPCallerIdentity | undefined {\n const owner =\n process.env.AGENT_NATIVE_OWNER_EMAIL?.trim() ||\n (typeof ownerEmailHeader === \"string\" && ownerEmailHeader.trim()) ||\n \"\";\n if (!owner) return undefined;\n return { userEmail: owner, orgDomain: undefined };\n}\n\nfunction addSecretCandidate(\n candidates: string[],\n secret: string | null | undefined,\n): void {\n const trimmed = secret?.trim();\n if (!trimmed || candidates.includes(trimmed)) return;\n candidates.push(trimmed);\n}\n\nasync function verifyA2AJwtForMcp(\n token: string,\n): Promise<Record<string, unknown> | null> {\n const jose = await import(\"jose\");\n let unverifiedPayload: Record<string, unknown> | null = null;\n try {\n unverifiedPayload = jose.decodeJwt(token) as Record<string, unknown>;\n } catch {\n return null;\n }\n\n const candidateSecrets: string[] = [];\n addSecretCandidate(candidateSecrets, process.env.A2A_SECRET);\n\n const orgDomain =\n typeof unverifiedPayload.org_domain === \"string\"\n ? unverifiedPayload.org_domain\n : undefined;\n if (orgDomain) {\n try {\n const { getA2ASecretByDomain } = await import(\"../org/context.js\");\n addSecretCandidate(\n candidateSecrets,\n await getA2ASecretByDomain(orgDomain),\n );\n } catch {\n // DB not ready or org lookup unavailable — fall back to other candidates.\n }\n }\n\n for (const secret of candidateSecrets) {\n try {\n const { payload } = await jose.jwtVerify(\n token,\n new TextEncoder().encode(secret),\n );\n return payload as Record<string, unknown>;\n } catch {\n // Try the next candidate without exposing which secret matched.\n }\n }\n\n return null;\n}\n\n/**\n * Verify the inbound auth header. Returns:\n * - { authed: true, identity } when verified — `identity` is derived from\n * the JWT (`sub` / `org_domain`) for JWT auth, or from the\n * `AGENT_NATIVE_OWNER_EMAIL` env / `X-Agent-Native-Owner-Email` header\n * for static-token auth (the `agent-native mcp install` flow). `identity`\n * is undefined only for true dev-open with no owner hint.\n * - { authed: false } on rejection.\n *\n * When A2A_SECRET is set we extract the JWT's `sub` (caller email) and\n * `org_domain` claims so the MCP endpoint can wrap tool runs in\n * `runWithRequestContext({ userEmail, orgId })`. Without that wrap, the\n * MCP endpoint loses tenant identity and downstream `accessFilter` /\n * `resolveCredential` calls fall back to platform-wide defaults.\n *\n * `ownerEmailHeader` is the forwarded `X-Agent-Native-Owner-Email` value; it\n * is consulted ONLY on the static-token / dev-open path (never to influence\n * verified JWT identity), so the install flow runs tools as the configured\n * owner instead of an unscoped anonymous caller.\n */\nexport async function verifyAuth(\n authHeader: string | undefined,\n ownerEmailHeader?: string | undefined,\n options: { allowDevOpen?: boolean; resourceUrl?: string } = {},\n): Promise<{\n authed: boolean;\n identity?: MCPCallerIdentity;\n /**\n * The caller presented a real credential — a verified A2A/connect JWT, a\n * matching ACCESS_TOKEN, or (on the no-auth-configured path) a forwarded\n * owner-email header from `agent-native mcp install`. Drives the full vs\n * sparse MCP tool surface in local dev. The pure unauthenticated dev-open\n * path (no secret, no token, no owner header) is `false`.\n */\n fullSurface?: boolean;\n}> {\n // No auth configured → allow only when the route caller has already\n // established that this is a loopback/local dev request. Still honour an\n // owner hint there so the local install/connect flow stays tenant-scoped.\n const accessTokens = getAccessTokens();\n const hasA2ASecret = !!process.env.A2A_SECRET;\n const token = authHeader?.startsWith(\"Bearer \")\n ? authHeader.slice(7)\n : undefined;\n if (token) {\n const oauthIdentity = await verifyMcpOAuthAccessToken(\n token,\n options.resourceUrl,\n );\n if (oauthIdentity) {\n return {\n authed: true,\n identity: {\n userEmail: oauthIdentity.userEmail,\n orgDomain: oauthIdentity.orgDomain,\n oauthScopes: oauthIdentity.scopes,\n oauthClientId: oauthIdentity.clientId,\n },\n fullSurface: true,\n };\n }\n }\n if (accessTokens.length === 0 && !hasA2ASecret && !token) {\n if (options.allowDevOpen === false) {\n return { authed: false };\n }\n return {\n authed: true,\n identity: deriveStaticTokenIdentity(ownerEmailHeader),\n // `mcp install`'s stdio proxy forwards an owner-email header even when\n // the local app has no secret configured — that is a real, identified\n // caller and gets the full surface. A bare browser/curl dev probe with\n // no owner hint stays on the sparse dev surface.\n fullSurface: !!(ownerEmailHeader && ownerEmailHeader.trim()),\n };\n }\n\n if (!token) return { authed: false };\n\n // Try an A2A JWT via the shared A2A_SECRET first, then the caller org's\n // synced A2A secret when the token carries org_domain.\n const payload = await verifyA2AJwtForMcp(token);\n if (payload) {\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 signature was already\n // cryptographically verified, so failing open here only widens the\n // explicit-revoke gate, never the trust boundary.\n if (tokenScope === MCP_CONNECT_SCOPE) {\n if (typeof payload.jti !== \"string\" || !payload.jti) {\n return { authed: false };\n }\n const jti = payload.jti;\n try {\n const { isJtiRevoked, touchTokenUsed } =\n await import(\"./connect-store.js\");\n if (await isJtiRevoked(jti)) {\n return { authed: false };\n }\n // Best-effort usage telemetry — never blocks / throws.\n void touchTokenUsed(jti);\n } catch {\n // Store import / lookup failed — fail open (see comment above).\n }\n }\n\n return {\n authed: true,\n identity: {\n userEmail: typeof payload.sub === \"string\" ? payload.sub : undefined,\n orgDomain:\n typeof payload.org_domain === \"string\"\n ? (payload.org_domain as string)\n : undefined,\n },\n // Verified JWT (connect-minted or A2A delegation) — a real caller.\n fullSurface: true,\n };\n }\n\n if (accessTokens.length === 0 && !hasA2ASecret) {\n if (options.allowDevOpen === false) {\n return { authed: false };\n }\n return {\n authed: true,\n identity: deriveStaticTokenIdentity(ownerEmailHeader),\n fullSurface: !!(ownerEmailHeader && ownerEmailHeader.trim()),\n };\n }\n\n // Try ACCESS_TOKEN / ACCESS_TOKENS exact match. Static tokens carry no\n // per-caller claims, so derive identity from the forwarded owner-email\n // hint (install flow) — otherwise tools would run unscoped.\n if (accessTokens.length > 0 && accessTokens.includes(token)) {\n return {\n authed: true,\n identity: deriveStaticTokenIdentity(ownerEmailHeader),\n // Matched a configured ACCESS_TOKEN — a real caller.\n fullSurface: true,\n };\n }\n\n return { authed: false };\n}\n\nexport async function resolveOrgIdFromDomain(\n orgDomain: string | undefined,\n): Promise<string | undefined> {\n if (!orgDomain) return undefined;\n try {\n const { resolveOrgByDomain } = await import(\"../org/context.js\");\n const org = await resolveOrgByDomain(orgDomain);\n return org?.orgId ?? undefined;\n } catch {\n return undefined;\n }\n}\n"]}
@@ -9,20 +9,16 @@
9
9
  * this helper every db-* CLI run hands the user a stack trace.
10
10
  *
11
11
  * What this does: when the runner is about to dispatch, resolve a real
12
- * email by reading the most-recent row from the legacy `sessions` table
13
- * (the same table that `addSession()` writes from google-oauth.ts and the
14
- * A2A receiver fallback already consults). The runner then wraps dispatch
15
- * in `runWithRequestContext({ userEmail })` so the action sees a real
16
- * identity.
12
+ * email from the legacy `sessions` table (the same table that
13
+ * `addSession()` writes from google-oauth.ts and the A2A receiver fallback
14
+ * already consults). The runner then wraps dispatch in
15
+ * `runWithRequestContext({ userEmail })` so the action sees a real identity.
17
16
  *
18
- * SHARED-DEV-BOX CAVEAT: the `SELECT email FROM sessions ORDER BY
19
- * created_at DESC LIMIT 1` query is unscoped on a machine where
20
- * multiple developers have signed in (or after a `pnpm action …` run
21
- * from another team's app), this will bind to whoever signed in most
22
- * recently across *all* sessions in the DB. If that is wrong, set
23
- * `AGENT_USER_EMAIL=<your-email>` in your shell or `.env`; explicit env
24
- * always wins. A `[dev-session]` log line is emitted so wrong-binding
25
- * is easy to spot.
17
+ * SHARED-DEV-BOX CAVEAT: this table is unscoped. To avoid silently binding
18
+ * to another developer, auto-binding only happens when the table contains
19
+ * exactly one distinct real email. If multiple developers have signed in,
20
+ * set `AGENT_USER_EMAIL=<your-email>` in your shell or `.env`; explicit env
21
+ * always wins.
26
22
  *
27
23
  * Strict gating mirrors the A2A precedent in
28
24
  * `server/agent-chat-plugin.ts` (search for "latest session"):
@@ -1 +1 @@
1
- {"version":3,"file":"dev-session.d.ts","sourceRoot":"","sources":["../../src/scripts/dev-session.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AAIH;;;;;;;GAOG;AACH,wBAAsB,mBAAmB,IAAI,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAkCvE"}
1
+ {"version":3,"file":"dev-session.d.ts","sourceRoot":"","sources":["../../src/scripts/dev-session.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAIH;;;;;;;GAOG;AACH,wBAAsB,mBAAmB,IAAI,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAoDvE"}
@@ -9,20 +9,16 @@
9
9
  * this helper every db-* CLI run hands the user a stack trace.
10
10
  *
11
11
  * What this does: when the runner is about to dispatch, resolve a real
12
- * email by reading the most-recent row from the legacy `sessions` table
13
- * (the same table that `addSession()` writes from google-oauth.ts and the
14
- * A2A receiver fallback already consults). The runner then wraps dispatch
15
- * in `runWithRequestContext({ userEmail })` so the action sees a real
16
- * identity.
12
+ * email from the legacy `sessions` table (the same table that
13
+ * `addSession()` writes from google-oauth.ts and the A2A receiver fallback
14
+ * already consults). The runner then wraps dispatch in
15
+ * `runWithRequestContext({ userEmail })` so the action sees a real identity.
17
16
  *
18
- * SHARED-DEV-BOX CAVEAT: the `SELECT email FROM sessions ORDER BY
19
- * created_at DESC LIMIT 1` query is unscoped on a machine where
20
- * multiple developers have signed in (or after a `pnpm action …` run
21
- * from another team's app), this will bind to whoever signed in most
22
- * recently across *all* sessions in the DB. If that is wrong, set
23
- * `AGENT_USER_EMAIL=<your-email>` in your shell or `.env`; explicit env
24
- * always wins. A `[dev-session]` log line is emitted so wrong-binding
25
- * is easy to spot.
17
+ * SHARED-DEV-BOX CAVEAT: this table is unscoped. To avoid silently binding
18
+ * to another developer, auto-binding only happens when the table contains
19
+ * exactly one distinct real email. If multiple developers have signed in,
20
+ * set `AGENT_USER_EMAIL=<your-email>` in your shell or `.env`; explicit env
21
+ * always wins.
26
22
  *
27
23
  * Strict gating mirrors the A2A precedent in
28
24
  * `server/agent-chat-plugin.ts` (search for "latest session"):
@@ -59,14 +55,28 @@ export async function resolveDevUserEmail() {
59
55
  try {
60
56
  const { getDbExec } = await import("../db/client.js");
61
57
  const { rows } = await getDbExec().execute({
62
- sql: `SELECT email FROM sessions
63
- WHERE email IS NOT NULL AND email <> ?
64
- ORDER BY created_at DESC LIMIT 1`,
58
+ sql: `SELECT email
59
+ FROM (
60
+ SELECT TRIM(email) AS email, MAX(created_at) AS last_seen
61
+ FROM sessions
62
+ WHERE email IS NOT NULL AND TRIM(email) <> ?
63
+ GROUP BY TRIM(email)
64
+ ) AS session_owners
65
+ WHERE email <> ''
66
+ ORDER BY last_seen DESC
67
+ LIMIT 2`,
65
68
  args: [DEV_FALLBACK_EMAIL],
66
69
  });
67
- const email = rows[0]?.email;
68
- if (!email || email.trim().length === 0)
70
+ const emails = rows
71
+ .map((row) => (typeof row.email === "string" ? row.email.trim() : ""))
72
+ .filter((email) => email.length > 0);
73
+ if (emails.length === 0)
69
74
  return undefined;
75
+ if (emails.length > 1) {
76
+ console.warn(`[dev-session] multiple session owners found (${emails.join(", ")}); set AGENT_USER_EMAIL=<email> to choose one`);
77
+ return undefined;
78
+ }
79
+ const email = emails[0];
70
80
  console.log(`[dev-session] auto-bound to ${email} (set AGENT_USER_EMAIL to override)`);
71
81
  return email;
72
82
  }
@@ -1 +1 @@
1
- {"version":3,"file":"dev-session.js","sourceRoot":"","sources":["../../src/scripts/dev-session.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AAEH,MAAM,kBAAkB,GAAG,iBAAiB,CAAC,CAAC,qGAAqG;AAEnJ;;;;;;;GAOG;AACH,MAAM,CAAC,KAAK,UAAU,mBAAmB;IACvC,MAAM,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,gBAAgB,CAAC;IAC9C,IAAI,QAAQ;QAAE,OAAO,QAAQ,CAAC;IAE9B,gEAAgE;IAChE,IAAI,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,YAAY;QAAE,OAAO,SAAS,CAAC;IAE5D,sEAAsE;IACtE,oEAAoE;IACpE,+BAA+B;IAC/B,MAAM,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC;IACvC,IAAI,QAAQ,IAAI,QAAQ,KAAK,OAAO;QAAE,OAAO,SAAS,CAAC;IAEvD,IAAI,CAAC;QACH,MAAM,EAAE,SAAS,EAAE,GAAG,MAAM,MAAM,CAAC,iBAAiB,CAAC,CAAC;QACtD,MAAM,EAAE,IAAI,EAAE,GAAG,MAAM,SAAS,EAAE,CAAC,OAAO,CAAC;YACzC,GAAG,EAAE;;6CAEkC;YACvC,IAAI,EAAE,CAAC,kBAAkB,CAAC;SAC3B,CAAC,CAAC;QACH,MAAM,KAAK,GAAG,IAAI,CAAC,CAAC,CAAC,EAAE,KAA2B,CAAC;QACnD,IAAI,CAAC,KAAK,IAAI,KAAK,CAAC,IAAI,EAAE,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO,SAAS,CAAC;QAC1D,OAAO,CAAC,GAAG,CACT,+BAA+B,KAAK,qCAAqC,CAC1E,CAAC;QACF,OAAO,KAAK,CAAC;IACf,CAAC;IAAC,MAAM,CAAC;QACP,oEAAoE;QACpE,kEAAkE;QAClE,+DAA+D;QAC/D,mCAAmC;QACnC,OAAO,SAAS,CAAC;IACnB,CAAC;AACH,CAAC","sourcesContent":["/**\n * Dev-only session bootstrap for `pnpm action <name>` (and any other CLI\n * caller of `runScript`).\n *\n * After changes-53, db-exec / db-query / db-patch refuse to run unless\n * `getRequestUserEmail()` returns a real identity. In an HTTP request the\n * Nitro plugin wraps the handler in `runWithRequestContext({ userEmail })`\n * so scoping just works. CLI invocations have no such wrapper, so without\n * this helper every db-* CLI run hands the user a stack trace.\n *\n * What this does: when the runner is about to dispatch, resolve a real\n * email by reading the most-recent row from the legacy `sessions` table\n * (the same table that `addSession()` writes from google-oauth.ts and the\n * A2A receiver fallback already consults). The runner then wraps dispatch\n * in `runWithRequestContext({ userEmail })` so the action sees a real\n * identity.\n *\n * SHARED-DEV-BOX CAVEAT: the `SELECT email FROM sessions ORDER BY\n * created_at DESC LIMIT 1` query is unscoped on a machine where\n * multiple developers have signed in (or after a `pnpm action …` run\n * from another team's app), this will bind to whoever signed in most\n * recently across *all* sessions in the DB. If that is wrong, set\n * `AGENT_USER_EMAIL=<your-email>` in your shell or `.env`; explicit env\n * always wins. A `[dev-session]` log line is emitted so wrong-binding\n * is easy to spot.\n *\n * Strict gating mirrors the A2A precedent in\n * `server/agent-chat-plugin.ts` (search for \"latest session\"):\n * - NODE_ENV !== \"production\".\n * - AUTH_MODE unset or === \"local\" — don't auto-impersonate when an\n * admin or hosted auth mode is in use.\n *\n * If `process.env.AGENT_USER_EMAIL` is already set we return it unchanged\n * — explicit env wins over any DB-derived guess (matches how\n * `getRequestUserEmail()` itself behaves).\n */\n\nconst DEV_FALLBACK_EMAIL = \"local@localhost\"; // guard:allow-localhost-fallback — sentinel intentionally rejected so the resolver doesn't return it\n\n/**\n * Resolve the local dev user's email for the current CLI invocation.\n *\n * Returns the resolved email, or `undefined` when no real identity is\n * available. Callers should let the downstream \"no authenticated user\"\n * error propagate — its message points the user at the two fixes\n * (sign in via the running app, or set `AGENT_USER_EMAIL`).\n */\nexport async function resolveDevUserEmail(): Promise<string | undefined> {\n const explicit = process.env.AGENT_USER_EMAIL;\n if (explicit) return explicit;\n\n // Hard refusal: this helper must never source identity in prod.\n if (process.env.NODE_ENV === \"production\") return undefined;\n\n // AUTH_MODE may be unset (default dev shim) or \"local\". Anything else\n // means a non-dev auth mode is in play; don't try to fish a session\n // out of the DB on its behalf.\n const authMode = process.env.AUTH_MODE;\n if (authMode && authMode !== \"local\") return undefined;\n\n try {\n const { getDbExec } = await import(\"../db/client.js\");\n const { rows } = await getDbExec().execute({\n sql: `SELECT email FROM sessions\n WHERE email IS NOT NULL AND email <> ?\n ORDER BY created_at DESC LIMIT 1`,\n args: [DEV_FALLBACK_EMAIL],\n });\n const email = rows[0]?.email as string | undefined;\n if (!email || email.trim().length === 0) return undefined;\n console.log(\n `[dev-session] auto-bound to ${email} (set AGENT_USER_EMAIL to override)`,\n );\n return email;\n } catch {\n // The sessions table doesn't exist yet (fresh install where the web\n // server has never booted) or the DB isn't reachable. Either way,\n // we can't produce an identity — let the caller throw with the\n // friendlier \"sign in first\" hint.\n return undefined;\n }\n}\n"]}
1
+ {"version":3,"file":"dev-session.js","sourceRoot":"","sources":["../../src/scripts/dev-session.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAEH,MAAM,kBAAkB,GAAG,iBAAiB,CAAC,CAAC,qGAAqG;AAEnJ;;;;;;;GAOG;AACH,MAAM,CAAC,KAAK,UAAU,mBAAmB;IACvC,MAAM,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,gBAAgB,CAAC;IAC9C,IAAI,QAAQ;QAAE,OAAO,QAAQ,CAAC;IAE9B,gEAAgE;IAChE,IAAI,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,YAAY;QAAE,OAAO,SAAS,CAAC;IAE5D,sEAAsE;IACtE,oEAAoE;IACpE,+BAA+B;IAC/B,MAAM,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC;IACvC,IAAI,QAAQ,IAAI,QAAQ,KAAK,OAAO;QAAE,OAAO,SAAS,CAAC;IAEvD,IAAI,CAAC;QACH,MAAM,EAAE,SAAS,EAAE,GAAG,MAAM,MAAM,CAAC,iBAAiB,CAAC,CAAC;QACtD,MAAM,EAAE,IAAI,EAAE,GAAG,MAAM,SAAS,EAAE,CAAC,OAAO,CAAC;YACzC,GAAG,EAAE;;;;;;;;;oBASS;YACd,IAAI,EAAE,CAAC,kBAAkB,CAAC;SAC3B,CAAC,CAAC;QACH,MAAM,MAAM,GAAG,IAAI;aAChB,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,OAAO,GAAG,CAAC,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;aACrE,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;QACvC,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC;YAAE,OAAO,SAAS,CAAC;QAC1C,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACtB,OAAO,CAAC,IAAI,CACV,gDAAgD,MAAM,CAAC,IAAI,CACzD,IAAI,CACL,+CAA+C,CACjD,CAAC;YACF,OAAO,SAAS,CAAC;QACnB,CAAC;QACD,MAAM,KAAK,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;QACxB,OAAO,CAAC,GAAG,CACT,+BAA+B,KAAK,qCAAqC,CAC1E,CAAC;QACF,OAAO,KAAK,CAAC;IACf,CAAC;IAAC,MAAM,CAAC;QACP,oEAAoE;QACpE,kEAAkE;QAClE,+DAA+D;QAC/D,mCAAmC;QACnC,OAAO,SAAS,CAAC;IACnB,CAAC;AACH,CAAC","sourcesContent":["/**\n * Dev-only session bootstrap for `pnpm action <name>` (and any other CLI\n * caller of `runScript`).\n *\n * After changes-53, db-exec / db-query / db-patch refuse to run unless\n * `getRequestUserEmail()` returns a real identity. In an HTTP request the\n * Nitro plugin wraps the handler in `runWithRequestContext({ userEmail })`\n * so scoping just works. CLI invocations have no such wrapper, so without\n * this helper every db-* CLI run hands the user a stack trace.\n *\n * What this does: when the runner is about to dispatch, resolve a real\n * email from the legacy `sessions` table (the same table that\n * `addSession()` writes from google-oauth.ts and the A2A receiver fallback\n * already consults). The runner then wraps dispatch in\n * `runWithRequestContext({ userEmail })` so the action sees a real identity.\n *\n * SHARED-DEV-BOX CAVEAT: this table is unscoped. To avoid silently binding\n * to another developer, auto-binding only happens when the table contains\n * exactly one distinct real email. If multiple developers have signed in,\n * set `AGENT_USER_EMAIL=<your-email>` in your shell or `.env`; explicit env\n * always wins.\n *\n * Strict gating mirrors the A2A precedent in\n * `server/agent-chat-plugin.ts` (search for \"latest session\"):\n * - NODE_ENV !== \"production\".\n * - AUTH_MODE unset or === \"local\" — don't auto-impersonate when an\n * admin or hosted auth mode is in use.\n *\n * If `process.env.AGENT_USER_EMAIL` is already set we return it unchanged\n * — explicit env wins over any DB-derived guess (matches how\n * `getRequestUserEmail()` itself behaves).\n */\n\nconst DEV_FALLBACK_EMAIL = \"local@localhost\"; // guard:allow-localhost-fallback — sentinel intentionally rejected so the resolver doesn't return it\n\n/**\n * Resolve the local dev user's email for the current CLI invocation.\n *\n * Returns the resolved email, or `undefined` when no real identity is\n * available. Callers should let the downstream \"no authenticated user\"\n * error propagate — its message points the user at the two fixes\n * (sign in via the running app, or set `AGENT_USER_EMAIL`).\n */\nexport async function resolveDevUserEmail(): Promise<string | undefined> {\n const explicit = process.env.AGENT_USER_EMAIL;\n if (explicit) return explicit;\n\n // Hard refusal: this helper must never source identity in prod.\n if (process.env.NODE_ENV === \"production\") return undefined;\n\n // AUTH_MODE may be unset (default dev shim) or \"local\". Anything else\n // means a non-dev auth mode is in play; don't try to fish a session\n // out of the DB on its behalf.\n const authMode = process.env.AUTH_MODE;\n if (authMode && authMode !== \"local\") return undefined;\n\n try {\n const { getDbExec } = await import(\"../db/client.js\");\n const { rows } = await getDbExec().execute({\n sql: `SELECT email\n FROM (\n SELECT TRIM(email) AS email, MAX(created_at) AS last_seen\n FROM sessions\n WHERE email IS NOT NULL AND TRIM(email) <> ?\n GROUP BY TRIM(email)\n ) AS session_owners\n WHERE email <> ''\n ORDER BY last_seen DESC\n LIMIT 2`,\n args: [DEV_FALLBACK_EMAIL],\n });\n const emails = rows\n .map((row) => (typeof row.email === \"string\" ? row.email.trim() : \"\"))\n .filter((email) => email.length > 0);\n if (emails.length === 0) return undefined;\n if (emails.length > 1) {\n console.warn(\n `[dev-session] multiple session owners found (${emails.join(\n \", \",\n )}); set AGENT_USER_EMAIL=<email> to choose one`,\n );\n return undefined;\n }\n const email = emails[0];\n console.log(\n `[dev-session] auto-bound to ${email} (set AGENT_USER_EMAIL to override)`,\n );\n return email;\n } catch {\n // The sessions table doesn't exist yet (fresh install where the web\n // server has never booted) or the DB isn't reachable. Either way,\n // we can't produce an identity — let the caller throw with the\n // friendlier \"sign in first\" hint.\n return undefined;\n }\n}\n"]}
@@ -84,7 +84,7 @@ export async function runScript(options = {}) {
84
84
  // it, db-exec / db-query / db-patch and any action that calls
85
85
  // `getRequestUserEmail()` see no identity and refuse to run. The
86
86
  // resolver picks up `AGENT_USER_EMAIL` if explicitly set, otherwise
87
- // reads the most-recent signed-in session from the DB (dev-only,
87
+ // reads the DB session owner only when it is unambiguous (dev-only,
88
88
  // narrowly gated — see dev-session.ts).
89
89
  //
90
90
  // This wrap is intentionally a single point of injection: it covers
@@ -1 +1 @@
1
- {"version":3,"file":"runner.js","sourceRoot":"","sources":["../../src/scripts/runner.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,EAAE,aAAa,EAAE,MAAM,KAAK,CAAC;AACpC,OAAO,EAAE,WAAW,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AACpE,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAC9C,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,OAAO,EAAE,qBAAqB,EAAE,MAAM,8BAA8B,CAAC;AACrE,OAAO,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AACvD,OAAO,EAAE,kBAAkB,EAAE,MAAM,4BAA4B,CAAC;A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CAC3F,CAAC;IACF,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC","sourcesContent":["/**\n * Generic action dispatcher for @agent-native/core apps.\n *\n * Dynamically imports and runs actions from the app's actions/ directory.\n * Falls back to scripts/ directory for backwards compatibility, then to\n * core scripts (db-schema, db-query, db-exec, etc.) when no local action is found.\n *\n * Actions must export a default function: (args: string[]) => Promise<void>\n *\n * Usage: pnpm action <action-name> [--args]\n */\n\nimport path from \"path\";\nimport fs from \"fs\";\nimport { pathToFileURL } from \"url\";\nimport { coreScripts, getCoreScriptNames } from \"./core-scripts.js\";\nimport { closeDbExec } from \"../db/client.js\";\nimport { loadEnv } from \"./utils.js\";\nimport { runWithRequestContext } from \"../server/request-context.js\";\nimport { resolveDevUserEmail } from \"./dev-session.js\";\nimport { notifyActionChange } from \"../server/action-change.js\";\nimport type { ActionEntry } from \"../agent/production-agent.js\";\n\n// Load .env from cwd so DATABASE_URL and other vars are available to all actions.\nloadEnv();\n\nexport interface RunScriptOptions {\n /**\n * Actions contributed by packages rather than the app's local `actions/`\n * directory. Local app actions still win on name collision.\n */\n packageActions?: Record<string, ActionEntry>;\n /** Help-section label for package actions. */\n packageActionLabel?: string;\n}\n\nasync function runAppDbPluginIfPresent(): Promise<void> {\n const dbPluginPath = path.resolve(process.cwd(), \"server/plugins/db.ts\");\n if (!fs.existsSync(dbPluginPath)) return;\n\n const mod = await import(/* @vite-ignore */ pathToFileURL(dbPluginPath).href);\n const plugin = mod.default;\n if (typeof plugin === \"function\") {\n await plugin({});\n }\n}\n\n/**\n * Run the action dispatcher. Call this from your app's actions/run.ts (or scripts/run.ts):\n *\n * import { runScript } from \"@agent-native/core\";\n * runScript();\n */\nexport async function runScript(options: RunScriptOptions = {}): Promise<void> {\n const actionName = process.argv[2];\n\n if (!actionName || actionName === \"--help\") {\n console.log(`Usage: pnpm action <action-name> [--arg value ...]`);\n console.log(`\\nRun any action with --help for usage details.`);\n\n // List local actions (try actions/ first, then scripts/)\n const actionsDir = path.resolve(process.cwd(), \"actions\");\n const scriptsDir = path.resolve(process.cwd(), \"scripts\");\n const localDir = fs.existsSync(actionsDir) ? actionsDir : scriptsDir;\n if (fs.existsSync(localDir)) {\n const locals = fs\n .readdirSync(localDir)\n .filter((f) => f.endsWith(\".ts\") && f !== \"run.ts\")\n .map((f) => f.replace(/\\.ts$/, \"\"));\n if (locals.length > 0) {\n console.log(`\\nApp actions:`);\n for (const name of locals) {\n console.log(` ${name}`);\n }\n }\n }\n\n const packageActionNames = Object.keys(options.packageActions ?? {}).sort();\n if (packageActionNames.length > 0) {\n console.log(`\\n${options.packageActionLabel ?? \"Package actions\"}:`);\n for (const name of packageActionNames) {\n console.log(` ${name}`);\n }\n }\n\n // List core scripts\n const coreNames = getCoreScriptNames();\n if (coreNames.length > 0) {\n console.log(`\\nCore actions (built-in):`);\n for (const name of coreNames) {\n console.log(` ${name}`);\n }\n }\n\n process.exit(0);\n }\n\n // Validate action name (only allow alphanumeric + hyphens)\n if (!/^[a-z][a-z0-9-]*$/.test(actionName)) {\n console.error(`Error: Invalid action name \"${actionName}\"`);\n process.exit(1);\n }\n\n const args = process.argv.slice(3);\n\n // Establish a request context for the duration of this CLI run. Without\n // it, db-exec / db-query / db-patch and any action that calls\n // `getRequestUserEmail()` see no identity and refuse to run. The\n // resolver picks up `AGENT_USER_EMAIL` if explicitly set, otherwise\n // reads the most-recent signed-in session from the DB (dev-only,\n // narrowly gated — see dev-session.ts).\n //\n // This wrap is intentionally a single point of injection: it covers\n // both the local-action branch and the fall-through to core scripts\n // (db-query, db-exec, …) so every CLI entrypoint runs scoped to a real\n // user. It uses `runWithRequestContext` rather than mutating\n // `process.env.AGENT_USER_EMAIL` because env mutation leaks across\n // boundaries — see the cautionary comment in\n // `server/request-context.ts` about exactly that pattern.\n const userEmail = await resolveDevUserEmail();\n const orgId = process.env.AGENT_ORG_ID || undefined;\n\n return runWithRequestContext({ userEmail, orgId }, () =>\n dispatchAction(actionName, args, options),\n );\n}\n\nfunction coerceCliValue(\n value: string,\n coerceBooleans: boolean,\n): string | boolean {\n if (!coerceBooleans) return value;\n if (value === \"true\") return true;\n if (value === \"false\") return false;\n return value;\n}\n\nfunction setParsedArg(\n parsed: Record<string, unknown>,\n key: string,\n value: unknown,\n) {\n const existing = parsed[key];\n if (existing === undefined) {\n parsed[key] = value;\n return;\n }\n parsed[key] = Array.isArray(existing)\n ? [...existing, value]\n : [existing, value];\n}\n\nfunction parseActionArgs(\n args: string[],\n options: { coerceBooleans?: boolean } = {},\n): Record<string, unknown> {\n const parsed: Record<string, unknown> = {};\n const coerceBooleans = options.coerceBooleans ?? false;\n for (let i = 0; i < args.length; i++) {\n const arg = args[i];\n if (!arg.startsWith(\"--\")) continue;\n const eqIdx = arg.indexOf(\"=\");\n if (eqIdx > 0) {\n setParsedArg(\n parsed,\n arg.slice(2, eqIdx),\n coerceCliValue(arg.slice(eqIdx + 1), coerceBooleans),\n );\n } else {\n const key = arg.slice(2);\n const next = args[i + 1];\n if (next && !next.startsWith(\"--\")) {\n setParsedArg(parsed, key, coerceCliValue(next, coerceBooleans));\n i++;\n } else {\n setParsedArg(parsed, key, coerceBooleans ? true : \"true\");\n }\n }\n }\n return parsed;\n}\n\nasync function dispatchAction(\n actionName: string,\n args: string[],\n options: RunScriptOptions,\n): Promise<void> {\n // 1. Try local app action first (actions/ then scripts/ for backwards compat)\n const actionsPath = path.resolve(\n process.cwd(),\n \"actions\",\n `${actionName}.ts`,\n );\n const scriptsPath = path.resolve(\n process.cwd(),\n \"scripts\",\n `${actionName}.ts`,\n );\n const localPath = fs.existsSync(actionsPath) ? actionsPath : scriptsPath;\n\n if (fs.existsSync(localPath)) {\n try {\n await runAppDbPluginIfPresent();\n const mod = await import(\n /* @vite-ignore */ pathToFileURL(localPath).href\n );\n const handler = mod.default;\n // Support defineAction-style default exports (object with run method)\n if (\n handler &&\n typeof handler === \"object\" &&\n typeof handler.run === \"function\"\n ) {\n const parsed = parseActionArgs(args, { coerceBooleans: true });\n const result = await handler.run(parsed);\n if (handler.readOnly !== true) {\n await notifyActionChange({ actionName }).catch(() => {});\n }\n if (result) console.log(result);\n } else if (typeof handler === \"function\") {\n await handler(args);\n } else {\n console.error(\n `Action \"${actionName}\" does not export a default function or defineAction.`,\n );\n process.exit(1);\n }\n await closeDbExec().catch(() => {});\n process.exit(0);\n } catch (err: any) {\n await closeDbExec().catch(() => {});\n console.error(`Action \"${actionName}\" failed:`, err.message || err);\n process.exit(1);\n }\n }\n\n // 2. Try package-contributed actions (e.g. @agent-native/dispatch)\n const packageAction = options.packageActions?.[actionName];\n if (packageAction) {\n try {\n await runAppDbPluginIfPresent();\n const parsed = parseActionArgs(args, { coerceBooleans: true });\n const result = await packageAction.run(parsed as Record<string, string>);\n if (packageAction.readOnly !== true) {\n await notifyActionChange({ actionName }).catch(() => {});\n }\n if (result) console.log(result);\n await closeDbExec().catch(() => {});\n process.exit(0);\n } catch (err: any) {\n await closeDbExec().catch(() => {});\n console.error(`Action \"${actionName}\" failed:`, err.message || err);\n process.exit(1);\n }\n }\n\n // 3. Fall back to core scripts\n const coreScript = coreScripts[actionName];\n if (coreScript) {\n try {\n await coreScript(args);\n await closeDbExec().catch(() => {});\n process.exit(0);\n } catch (err: any) {\n await closeDbExec().catch(() => {});\n console.error(`Core action \"${actionName}\" failed:`, err.message || err);\n process.exit(1);\n }\n }\n\n // 4. Not found anywhere\n console.error(\n `Error: Action \"${actionName}\" not found. Run \"pnpm action --help\" for available actions.`,\n );\n process.exit(1);\n}\n"]}
1
+ {"version":3,"file":"runner.js","sourceRoot":"","sources":["../../src/scripts/runner.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,EAAE,aAAa,EAAE,MAAM,KAAK,CAAC;AACpC,OAAO,EAAE,WAAW,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AACpE,OAA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AC,CAAC,CAAC;YACpC,OAAO,CAAC,KAAK,CAAC,gBAAgB,UAAU,WAAW,EAAE,GAAG,CAAC,OAAO,IAAI,GAAG,CAAC,CAAC;YACzE,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QAClB,CAAC;IACH,CAAC;IAED,wBAAwB;IACxB,OAAO,CAAC,KAAK,CACX,kBAAkB,UAAU,8DAA8D,CAC3F,CAAC;IACF,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC","sourcesContent":["/**\n * Generic action dispatcher for @agent-native/core apps.\n *\n * Dynamically imports and runs actions from the app's actions/ directory.\n * Falls back to scripts/ directory for backwards compatibility, then to\n * core scripts (db-schema, db-query, db-exec, etc.) when no local action is found.\n *\n * Actions must export a default function: (args: string[]) => Promise<void>\n *\n * Usage: pnpm action <action-name> [--args]\n */\n\nimport path from \"path\";\nimport fs from \"fs\";\nimport { pathToFileURL } from \"url\";\nimport { coreScripts, getCoreScriptNames } from \"./core-scripts.js\";\nimport { closeDbExec } from \"../db/client.js\";\nimport { loadEnv } from \"./utils.js\";\nimport { runWithRequestContext } from \"../server/request-context.js\";\nimport { resolveDevUserEmail } from \"./dev-session.js\";\nimport { notifyActionChange } from \"../server/action-change.js\";\nimport type { ActionEntry } from \"../agent/production-agent.js\";\n\n// Load .env from cwd so DATABASE_URL and other vars are available to all actions.\nloadEnv();\n\nexport interface RunScriptOptions {\n /**\n * Actions contributed by packages rather than the app's local `actions/`\n * directory. Local app actions still win on name collision.\n */\n packageActions?: Record<string, ActionEntry>;\n /** Help-section label for package actions. */\n packageActionLabel?: string;\n}\n\nasync function runAppDbPluginIfPresent(): Promise<void> {\n const dbPluginPath = path.resolve(process.cwd(), \"server/plugins/db.ts\");\n if (!fs.existsSync(dbPluginPath)) return;\n\n const mod = await import(/* @vite-ignore */ pathToFileURL(dbPluginPath).href);\n const plugin = mod.default;\n if (typeof plugin === \"function\") {\n await plugin({});\n }\n}\n\n/**\n * Run the action dispatcher. Call this from your app's actions/run.ts (or scripts/run.ts):\n *\n * import { runScript } from \"@agent-native/core\";\n * runScript();\n */\nexport async function runScript(options: RunScriptOptions = {}): Promise<void> {\n const actionName = process.argv[2];\n\n if (!actionName || actionName === \"--help\") {\n console.log(`Usage: pnpm action <action-name> [--arg value ...]`);\n console.log(`\\nRun any action with --help for usage details.`);\n\n // List local actions (try actions/ first, then scripts/)\n const actionsDir = path.resolve(process.cwd(), \"actions\");\n const scriptsDir = path.resolve(process.cwd(), \"scripts\");\n const localDir = fs.existsSync(actionsDir) ? actionsDir : scriptsDir;\n if (fs.existsSync(localDir)) {\n const locals = fs\n .readdirSync(localDir)\n .filter((f) => f.endsWith(\".ts\") && f !== \"run.ts\")\n .map((f) => f.replace(/\\.ts$/, \"\"));\n if (locals.length > 0) {\n console.log(`\\nApp actions:`);\n for (const name of locals) {\n console.log(` ${name}`);\n }\n }\n }\n\n const packageActionNames = Object.keys(options.packageActions ?? {}).sort();\n if (packageActionNames.length > 0) {\n console.log(`\\n${options.packageActionLabel ?? \"Package actions\"}:`);\n for (const name of packageActionNames) {\n console.log(` ${name}`);\n }\n }\n\n // List core scripts\n const coreNames = getCoreScriptNames();\n if (coreNames.length > 0) {\n console.log(`\\nCore actions (built-in):`);\n for (const name of coreNames) {\n console.log(` ${name}`);\n }\n }\n\n process.exit(0);\n }\n\n // Validate action name (only allow alphanumeric + hyphens)\n if (!/^[a-z][a-z0-9-]*$/.test(actionName)) {\n console.error(`Error: Invalid action name \"${actionName}\"`);\n process.exit(1);\n }\n\n const args = process.argv.slice(3);\n\n // Establish a request context for the duration of this CLI run. Without\n // it, db-exec / db-query / db-patch and any action that calls\n // `getRequestUserEmail()` see no identity and refuse to run. The\n // resolver picks up `AGENT_USER_EMAIL` if explicitly set, otherwise\n // reads the DB session owner only when it is unambiguous (dev-only,\n // narrowly gated — see dev-session.ts).\n //\n // This wrap is intentionally a single point of injection: it covers\n // both the local-action branch and the fall-through to core scripts\n // (db-query, db-exec, …) so every CLI entrypoint runs scoped to a real\n // user. It uses `runWithRequestContext` rather than mutating\n // `process.env.AGENT_USER_EMAIL` because env mutation leaks across\n // boundaries — see the cautionary comment in\n // `server/request-context.ts` about exactly that pattern.\n const userEmail = await resolveDevUserEmail();\n const orgId = process.env.AGENT_ORG_ID || undefined;\n\n return runWithRequestContext({ userEmail, orgId }, () =>\n dispatchAction(actionName, args, options),\n );\n}\n\nfunction coerceCliValue(\n value: string,\n coerceBooleans: boolean,\n): string | boolean {\n if (!coerceBooleans) return value;\n if (value === \"true\") return true;\n if (value === \"false\") return false;\n return value;\n}\n\nfunction setParsedArg(\n parsed: Record<string, unknown>,\n key: string,\n value: unknown,\n) {\n const existing = parsed[key];\n if (existing === undefined) {\n parsed[key] = value;\n return;\n }\n parsed[key] = Array.isArray(existing)\n ? [...existing, value]\n : [existing, value];\n}\n\nfunction parseActionArgs(\n args: string[],\n options: { coerceBooleans?: boolean } = {},\n): Record<string, unknown> {\n const parsed: Record<string, unknown> = {};\n const coerceBooleans = options.coerceBooleans ?? false;\n for (let i = 0; i < args.length; i++) {\n const arg = args[i];\n if (!arg.startsWith(\"--\")) continue;\n const eqIdx = arg.indexOf(\"=\");\n if (eqIdx > 0) {\n setParsedArg(\n parsed,\n arg.slice(2, eqIdx),\n coerceCliValue(arg.slice(eqIdx + 1), coerceBooleans),\n );\n } else {\n const key = arg.slice(2);\n const next = args[i + 1];\n if (next && !next.startsWith(\"--\")) {\n setParsedArg(parsed, key, coerceCliValue(next, coerceBooleans));\n i++;\n } else {\n setParsedArg(parsed, key, coerceBooleans ? true : \"true\");\n }\n }\n }\n return parsed;\n}\n\nasync function dispatchAction(\n actionName: string,\n args: string[],\n options: RunScriptOptions,\n): Promise<void> {\n // 1. Try local app action first (actions/ then scripts/ for backwards compat)\n const actionsPath = path.resolve(\n process.cwd(),\n \"actions\",\n `${actionName}.ts`,\n );\n const scriptsPath = path.resolve(\n process.cwd(),\n \"scripts\",\n `${actionName}.ts`,\n );\n const localPath = fs.existsSync(actionsPath) ? actionsPath : scriptsPath;\n\n if (fs.existsSync(localPath)) {\n try {\n await runAppDbPluginIfPresent();\n const mod = await import(\n /* @vite-ignore */ pathToFileURL(localPath).href\n );\n const handler = mod.default;\n // Support defineAction-style default exports (object with run method)\n if (\n handler &&\n typeof handler === \"object\" &&\n typeof handler.run === \"function\"\n ) {\n const parsed = parseActionArgs(args, { coerceBooleans: true });\n const result = await handler.run(parsed);\n if (handler.readOnly !== true) {\n await notifyActionChange({ actionName }).catch(() => {});\n }\n if (result) console.log(result);\n } else if (typeof handler === \"function\") {\n await handler(args);\n } else {\n console.error(\n `Action \"${actionName}\" does not export a default function or defineAction.`,\n );\n process.exit(1);\n }\n await closeDbExec().catch(() => {});\n process.exit(0);\n } catch (err: any) {\n await closeDbExec().catch(() => {});\n console.error(`Action \"${actionName}\" failed:`, err.message || err);\n process.exit(1);\n }\n }\n\n // 2. Try package-contributed actions (e.g. @agent-native/dispatch)\n const packageAction = options.packageActions?.[actionName];\n if (packageAction) {\n try {\n await runAppDbPluginIfPresent();\n const parsed = parseActionArgs(args, { coerceBooleans: true });\n const result = await packageAction.run(parsed as Record<string, string>);\n if (packageAction.readOnly !== true) {\n await notifyActionChange({ actionName }).catch(() => {});\n }\n if (result) console.log(result);\n await closeDbExec().catch(() => {});\n process.exit(0);\n } catch (err: any) {\n await closeDbExec().catch(() => {});\n console.error(`Action \"${actionName}\" failed:`, err.message || err);\n process.exit(1);\n }\n }\n\n // 3. Fall back to core scripts\n const coreScript = coreScripts[actionName];\n if (coreScript) {\n try {\n await coreScript(args);\n await closeDbExec().catch(() => {});\n process.exit(0);\n } catch (err: any) {\n await closeDbExec().catch(() => {});\n console.error(`Core action \"${actionName}\" failed:`, err.message || err);\n process.exit(1);\n }\n }\n\n // 4. Not found anywhere\n console.error(\n `Error: Action \"${actionName}\" not found. Run \"pnpm action --help\" for available actions.`,\n );\n process.exit(1);\n}\n"]}
@@ -152,7 +152,7 @@ If your app is an [A2A](/docs/a2a-protocol) peer, other agent-native apps discov
152
152
 
153
153
  ## Exposing it over MCP {#mcp}
154
154
 
155
- With MCP enabled, your actions show up in the framework's MCP server at `/_agent-native/mcp`. Stdio/static-token developer clients see the full connected action surface. OAuth app hosts that request `mcp:apps` get a compact catalog containing app-facing builtins and actions with `mcpApp`; `publicAgent.expose` is still the opt-in for safe read/ingest tools outside that compact app catalog. See [MCP Protocol](/docs/mcp-protocol).
155
+ With MCP enabled, your actions show up in the framework's MCP server at `/_agent-native/mcp`. Stdio/static-token developer clients see the full connected action surface. OAuth app hosts that request `mcp:apps` get a compact catalog containing app-facing builtins (`open_app`, `list_apps`, `ask_app`, and app-only embed helpers); action-specific MCP App resources stay out of that catalog unless an action explicitly sets `mcpApp.compactCatalog: true`. `publicAgent.expose` is still the opt-in for safe read/ingest tools outside that compact app catalog. See [MCP Protocol](/docs/mcp-protocol).
156
156
 
157
157
  For UI-capable MCP hosts, actions can also attach an optional MCP Apps resource.
158
158
  Use the shared full-app embed helper when the action needs an inline experience.
@@ -81,6 +81,10 @@ message, so it stays model-visible without being posted as user-facing chat.
81
81
  `submit: false` keeps the local prefill/review behavior because MCP Apps do not
82
82
  define a standard draft-prefill API.
83
83
 
84
+ Internally this is the submitted-chat path sometimes surfaced as
85
+ `agentNative.submitChat`; app code should call `sendToAgentChat()` rather than
86
+ posting that event directly.
87
+
84
88
  ```ts
85
89
  import { sendToAgentChat } from "@agent-native/core";
86
90
 
@@ -56,6 +56,11 @@ selected app grants, so external agents can route work to Mail, Calendar,
56
56
  Analytics, Brain, and workspace apps without a separate authorization for every
57
57
  app.
58
58
 
59
+ When a host supports MCP Apps, that same Dispatch connector can render granted
60
+ app routes inline too: email drafts, calendar invites, decks, forms, docs,
61
+ designs, dashboards, clips, and other app routes can preview in chat without
62
+ adding per-app connectors.
63
+
59
64
  Direct per-app MCP URLs such as
60
65
  `https://mail.agent-native.com/_agent-native/mcp` still exist when you
61
66
  intentionally want one isolated app surface. For most workspace use, the
@@ -122,6 +122,10 @@ import { sendToAgentChat } from "@agent-native/core/client";
122
122
 
123
123
  `sendToAgentChat` returns a stable `tabId` you can use to track the chat run.
124
124
 
125
+ When the same route is embedded as an MCP App, submitted
126
+ `sendToAgentChat()` calls are forwarded to the host chat where supported; see
127
+ [Client](/docs/client#sendtoagentchat) for the MCP App bridge behavior.
128
+
125
129
  If you want a loading state, use the `useSendToAgentChat()` hook — it returns both `send` and `isGenerating`:
126
130
 
127
131
  ```ts
@@ -177,10 +177,9 @@ host. Developer clients and bearer/static-token clients get the app's full
177
177
  action surface plus the `ask-agent` meta-tool that runs the full agent loop
178
178
  (the same entry point [A2A](/docs/a2a-protocol) uses). OAuth chat hosts that
179
179
  request `mcp:apps`, including Claude and ChatGPT, get a compact app-facing
180
- catalog instead: cross-app verbs such as `list_apps` and `open_app`, app-only
181
- embed helpers, and actions that explicitly declare `mcpApp`. In both cases,
182
- ask the agent to do real work and it hands back a link straight into the
183
- running app:
180
+ catalog instead: cross-app verbs such as `list_apps`, `open_app`, and
181
+ `ask_app`, plus the app-only embed helper. In both cases, ask the agent to do
182
+ real work and it hands back a link straight into the running app:
184
183
 
185
184
  ```
186
185
  > draft an email to John about the Q3 report
@@ -201,6 +200,14 @@ declares `mcpApp`, the server advertises
201
200
  security metadata such as CSP and sandbox permissions lives on the resource
202
201
  entries and `resources/read` content, not on the tool descriptor.
203
202
 
203
+ For ChatGPT/Claude-style OAuth app hosts, that discovery surface is compact by
204
+ default: `tools/list` and `resources/list` advertise the generic `open_app`
205
+ embed path instead of every action-specific MCP App resource. Use
206
+ `open_app({ path, embed: true })` for first-class inline app previews. Keep
207
+ action-specific MCP App resources for direct app connectors that disable the
208
+ generic builtins, or mark an individual action with `mcpApp.compactCatalog: true`
209
+ only when it truly needs to stay visible in chat-host discovery.
210
+
204
211
  That makes the same app surface available to every compatible host rather than building per-client shims. The current official MCP Apps client list includes Claude, Claude Desktop, VS Code GitHub Copilot, Goose, Postman, MCPJam, ChatGPT, and Cursor; host support still varies by plan, release channel, and client version, so check the [MCP extension support matrix](https://modelcontextprotocol.io/extensions/client-matrix). ChatGPT custom MCP apps are available through developer mode for Business and Enterprise/Edu workspaces on ChatGPT web; see OpenAI's [developer mode and MCP apps](https://help.openai.com/en/articles/12584461-developer-mode-and-full-mcp-apps-in-chatgpt-beta) notes.
205
212
 
206
213
  Claude Code and other CLI-first clients still receive the same resources and metadata when they support MCP Apps, but the deep link remains the reliable fallback when a host chooses not to render an iframe. In practice, every agent-native app should be authored with both: MCP Apps for inline review/edit in capable hosts, and `link` for universal round-tripping back to the full app.
@@ -310,7 +317,16 @@ On top of the per-action tools the MCP server exposes a stable verb set, so an e
310
317
 
311
318
  `create_workspace_app` rejects any non-allow-listed template — the public template allow-list in `packages/shared-app-config/templates.ts` is authoritative and CI-guarded; an external agent cannot widen it. A same-named template action overrides a builtin (template-over-core precedence). Disable the whole set with `MCPConfig.builtinCrossAppTools: false`.
312
319
 
313
- For OAuth callers that request `mcp:apps`, the server intentionally advertises a compact `tools/list` catalog so app hosts do not ingest every internal action schema. The model sees app-facing builtins (`list_apps`, `open_app`, app-only `create_embed_session`) and actions with `mcpApp`. Stdio/static-token developer clients still get the full connected action surface, and `publicAgent.expose` remains the opt-in for safe read/ingest tools outside the compact app catalog. If a UI-capable host should be able to call a new action from an MCP App conversation, mark it with `mcpApp`; use `publicAgent` for non-UI read/ingest handoff tools.
320
+ For OAuth callers that request `mcp:apps`, the server intentionally advertises
321
+ tiny `tools/list` and `resources/list` catalogs so app hosts do not ingest
322
+ every internal action schema or every action-specific UI resource. The model
323
+ sees app-facing builtins (`list_apps`, `open_app`, `ask_app`, and app-only
324
+ `create_embed_session`) and routes inline UI through
325
+ `open_app({ embed: true })`. Stdio/static-token developer clients still get
326
+ the full connected action surface, and `publicAgent.expose` remains the opt-in
327
+ for safe read/ingest tools outside the compact app catalog. If an individual
328
+ UI action must remain visible to ChatGPT/Claude discovery, set
329
+ `mcpApp.compactCatalog: true`, but treat that as a rare exception.
314
330
 
315
331
  For fast ChatGPT/Claude handoffs, the ideal path is direct: call the action that creates or opens the artifact, then let the MCP App launch the route. A Mail request should call `manage_draft` and render the real compose route. A dashboard request should call `open_app({ path, embed: true })` or a dashboard action with `mcpApp` and render the full Analytics route. Calendar, Forms, Content, Slides, Design, and Clips should follow the same pattern with their draft/create/search actions. `list_apps` is useful when the model must choose among granted apps; broad `resources/list`, full-catalog discovery, or `ask_app` delegation should not be the normal route for an obvious UI handoff.
316
332
 
@@ -571,5 +587,3 @@ The fallback hosted `connect` flow never copies the deployment's shared secret.
571
587
  - [A2A Protocol](/docs/a2a-protocol) — the `ask-agent` meta-tool and JSON-RPC peer calls.
572
588
  - [Actions](/docs/actions) — defining actions, `publicAgent`, GET / `readOnly`.
573
589
  - [Context Awareness](/docs/context-awareness) — the `navigate` / `application_state` contract the open route bridges to.
574
- </content>
575
- </invoke>
@@ -148,7 +148,7 @@ request. Embedded routes must remain functional in the default inline mode.
148
148
 
149
149
  ## Tools {#tools}
150
150
 
151
- Stdio/static-token developer clients see all connected app actions as MCP tools. OAuth callers that request `mcp:apps` get a compact app-host catalog: app-facing builtins and actions with `mcpApp`. `publicAgent.expose` remains the opt-in for safe read/ingest tools outside that compact app catalog. This keeps ChatGPT/Claude app-host discovery small while preserving the full developer surface for local agents.
151
+ Stdio/static-token developer clients see all connected app actions as MCP tools. OAuth callers that request `mcp:apps` get a compact app-host catalog: app-facing builtins (`list_apps`, `open_app`, `ask_app`, and app-only `create_embed_session`) plus rare actions marked `mcpApp.compactCatalog: true`. Their `resources/list` is compact too, normally advertising only the generic `open_app` embed resource. `publicAgent.expose` remains the opt-in for safe read/ingest tools outside that compact app catalog. This keeps ChatGPT/Claude app-host discovery small while preserving the full developer surface for local agents.
152
152
 
153
153
  The mapping is direct:
154
154
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agent-native/core",
3
- "version": "0.22.31",
3
+ "version": "0.22.33",
4
4
  "type": "module",
5
5
  "description": "Framework for agent-native application development — where AI agents and UI share state via files",
6
6
  "license": "MIT",