@agent-native/core 0.20.9 → 0.22.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/action.d.ts +61 -0
- package/dist/action.d.ts.map +1 -1
- package/dist/action.js +14 -0
- package/dist/action.js.map +1 -1
- package/dist/agent/production-agent.d.ts +4 -0
- package/dist/agent/production-agent.d.ts.map +1 -1
- package/dist/agent/production-agent.js +19 -7
- package/dist/agent/production-agent.js.map +1 -1
- package/dist/agent/types.d.ts +2 -0
- package/dist/agent/types.d.ts.map +1 -1
- package/dist/agent/types.js.map +1 -1
- package/dist/cli/code-agent-executor.d.ts.map +1 -1
- package/dist/cli/code-agent-executor.js +1 -0
- package/dist/cli/code-agent-executor.js.map +1 -1
- package/dist/cli/connect.d.ts +18 -3
- package/dist/cli/connect.d.ts.map +1 -1
- package/dist/cli/connect.js +619 -19
- package/dist/cli/connect.js.map +1 -1
- package/dist/client/AgentPanel.d.ts.map +1 -1
- package/dist/client/AgentPanel.js +6 -2
- package/dist/client/AgentPanel.js.map +1 -1
- package/dist/client/AssistantChat.d.ts.map +1 -1
- package/dist/client/AssistantChat.js +13 -6
- package/dist/client/AssistantChat.js.map +1 -1
- package/dist/client/NewWorkspaceAppFlow.js +1 -1
- package/dist/client/NewWorkspaceAppFlow.js.map +1 -1
- package/dist/client/agent-chat.d.ts.map +1 -1
- package/dist/client/agent-chat.js +13 -8
- package/dist/client/agent-chat.js.map +1 -1
- package/dist/client/agent-sidebar-state.d.ts +2 -0
- package/dist/client/agent-sidebar-state.d.ts.map +1 -1
- package/dist/client/agent-sidebar-state.js +40 -0
- package/dist/client/agent-sidebar-state.js.map +1 -1
- package/dist/client/code-agent-chat-adapter.js +1 -0
- package/dist/client/code-agent-chat-adapter.js.map +1 -1
- package/dist/client/conversation/AgentConversation.d.ts.map +1 -1
- package/dist/client/conversation/AgentConversation.js +3 -2
- package/dist/client/conversation/AgentConversation.js.map +1 -1
- package/dist/client/conversation/code-agent-transcript.js +1 -0
- package/dist/client/conversation/code-agent-transcript.js.map +1 -1
- package/dist/client/conversation/types.d.ts +2 -0
- package/dist/client/conversation/types.d.ts.map +1 -1
- package/dist/client/conversation/types.js.map +1 -1
- package/dist/client/index.d.ts +1 -0
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +1 -0
- package/dist/client/index.js.map +1 -1
- package/dist/client/mcp-apps/McpAppRenderer.d.ts +10 -0
- package/dist/client/mcp-apps/McpAppRenderer.d.ts.map +1 -0
- package/dist/client/mcp-apps/McpAppRenderer.js +301 -0
- package/dist/client/mcp-apps/McpAppRenderer.js.map +1 -0
- package/dist/client/sse-event-processor.d.ts +3 -0
- package/dist/client/sse-event-processor.d.ts.map +1 -1
- package/dist/client/sse-event-processor.js +2 -0
- package/dist/client/sse-event-processor.js.map +1 -1
- package/dist/client/use-db-sync.d.ts +5 -5
- package/dist/client/use-db-sync.d.ts.map +1 -1
- package/dist/client/use-db-sync.js +15 -5
- package/dist/client/use-db-sync.js.map +1 -1
- package/dist/client/use-db-sync.spec.d.ts +2 -0
- package/dist/client/use-db-sync.spec.d.ts.map +1 -0
- package/dist/client/use-db-sync.spec.js +80 -0
- package/dist/client/use-db-sync.spec.js.map +1 -0
- package/dist/code-agents/transcript-normalizer.d.ts +2 -0
- package/dist/code-agents/transcript-normalizer.d.ts.map +1 -1
- package/dist/code-agents/transcript-normalizer.js +17 -0
- package/dist/code-agents/transcript-normalizer.js.map +1 -1
- package/dist/db/client.d.ts.map +1 -1
- package/dist/db/client.js +29 -21
- package/dist/db/client.js.map +1 -1
- package/dist/extensions/actions.d.ts.map +1 -1
- package/dist/extensions/actions.js +62 -3
- package/dist/extensions/actions.js.map +1 -1
- package/dist/extensions/content-patch.d.ts +71 -0
- package/dist/extensions/content-patch.d.ts.map +1 -0
- package/dist/extensions/content-patch.js +251 -0
- package/dist/extensions/content-patch.js.map +1 -0
- package/dist/extensions/routes.js +6 -1
- package/dist/extensions/routes.js.map +1 -1
- package/dist/extensions/store.d.ts +4 -4
- package/dist/extensions/store.d.ts.map +1 -1
- package/dist/extensions/store.js +14 -18
- package/dist/extensions/store.js.map +1 -1
- package/dist/index.browser.d.ts +1 -1
- package/dist/index.browser.d.ts.map +1 -1
- package/dist/index.browser.js +1 -1
- package/dist/index.browser.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/mcp/build-server.d.ts +3 -0
- package/dist/mcp/build-server.d.ts.map +1 -1
- package/dist/mcp/build-server.js +207 -8
- package/dist/mcp/build-server.js.map +1 -1
- package/dist/mcp/oauth-route.d.ts +22 -0
- package/dist/mcp/oauth-route.d.ts.map +1 -0
- package/dist/mcp/oauth-route.js +618 -0
- package/dist/mcp/oauth-route.js.map +1 -0
- package/dist/mcp/oauth-store.d.ts +89 -0
- package/dist/mcp/oauth-store.d.ts.map +1 -0
- package/dist/mcp/oauth-store.js +391 -0
- package/dist/mcp/oauth-store.js.map +1 -0
- package/dist/mcp/oauth-token.d.ts +28 -0
- package/dist/mcp/oauth-token.d.ts.map +1 -0
- package/dist/mcp/oauth-token.js +83 -0
- package/dist/mcp/oauth-token.js.map +1 -0
- package/dist/mcp/server.d.ts.map +1 -1
- package/dist/mcp/server.js +5 -2
- package/dist/mcp/server.js.map +1 -1
- package/dist/mcp/stdio.d.ts +2 -2
- package/dist/mcp/stdio.d.ts.map +1 -1
- package/dist/mcp/stdio.js +26 -8
- package/dist/mcp/stdio.js.map +1 -1
- package/dist/mcp-client/app-result.d.ts +40 -0
- package/dist/mcp-client/app-result.d.ts.map +1 -0
- package/dist/mcp-client/app-result.js +19 -0
- package/dist/mcp-client/app-result.js.map +1 -0
- package/dist/mcp-client/index.d.ts +5 -2
- package/dist/mcp-client/index.d.ts.map +1 -1
- package/dist/mcp-client/index.js +201 -25
- package/dist/mcp-client/index.js.map +1 -1
- package/dist/mcp-client/manager.d.ts +16 -0
- package/dist/mcp-client/manager.d.ts.map +1 -1
- package/dist/mcp-client/manager.js +58 -1
- package/dist/mcp-client/manager.js.map +1 -1
- package/dist/mcp-client/routes.d.ts +4 -1
- package/dist/mcp-client/routes.d.ts.map +1 -1
- package/dist/mcp-client/routes.js +159 -0
- package/dist/mcp-client/routes.js.map +1 -1
- package/dist/scripts/dev/shell.d.ts.map +1 -1
- package/dist/scripts/dev/shell.js +24 -1
- package/dist/scripts/dev/shell.js.map +1 -1
- package/dist/server/agent-chat-plugin.d.ts.map +1 -1
- package/dist/server/agent-chat-plugin.js +3 -2
- package/dist/server/agent-chat-plugin.js.map +1 -1
- package/dist/server/auth.d.ts.map +1 -1
- package/dist/server/auth.js +14 -8
- package/dist/server/auth.js.map +1 -1
- package/dist/server/builder-browser.d.ts +6 -0
- package/dist/server/builder-browser.d.ts.map +1 -1
- package/dist/server/builder-browser.js +15 -0
- package/dist/server/builder-browser.js.map +1 -1
- package/dist/server/core-routes-plugin.d.ts +5 -4
- package/dist/server/core-routes-plugin.d.ts.map +1 -1
- package/dist/server/core-routes-plugin.js +17 -2
- package/dist/server/core-routes-plugin.js.map +1 -1
- package/dist/styles/agent-conversation.css +53 -0
- package/dist/templates/default/.agents/skills/actions/SKILL.md +193 -72
- package/dist/templates/default/.agents/skills/real-time-sync/SKILL.md +88 -38
- package/dist/templates/default/AGENTS.md +3 -3
- package/dist/templates/default/actions/hello.ts +13 -20
- package/dist/templates/default/actions/navigate.ts +19 -51
- package/dist/templates/default/actions/view-screen.ts +16 -33
- package/dist/templates/default/app/hooks/use-navigation-state.ts +13 -3
- package/dist/templates/default/app/lib/tab-id.ts +1 -0
- package/dist/templates/default/app/root.tsx +2 -1
- package/dist/templates/default/app/routes/_index.tsx +11 -0
- package/dist/templates/default/package.json +2 -1
- package/dist/templates/workspace-core/.agents/skills/real-time-sync/SKILL.md +9 -1
- package/dist/templates/workspace-core/AGENTS.md +8 -0
- package/dist/templates/workspace-root/AGENTS.md +7 -0
- package/dist/vite/client.d.ts.map +1 -1
- package/dist/vite/client.js +2 -2
- package/dist/vite/client.js.map +1 -1
- package/docs/content/actions.md +26 -3
- package/docs/content/authentication.md +16 -1
- package/docs/content/client.md +11 -8
- package/docs/content/context-awareness.md +2 -3
- package/docs/content/creating-templates.md +2 -2
- package/docs/content/external-agents.md +106 -19
- package/docs/content/faq.md +2 -2
- package/docs/content/key-concepts.md +31 -23
- package/docs/content/mcp-clients.md +1 -1
- package/docs/content/mcp-protocol.md +65 -27
- package/docs/content/template-starter.md +3 -3
- package/docs/content/what-is-agent-native.md +4 -2
- package/package.json +3 -1
- package/src/templates/default/.agents/skills/actions/SKILL.md +193 -72
- package/src/templates/default/.agents/skills/real-time-sync/SKILL.md +88 -38
- package/src/templates/default/AGENTS.md +3 -3
- package/src/templates/default/actions/hello.ts +13 -20
- package/src/templates/default/actions/navigate.ts +19 -51
- package/src/templates/default/actions/view-screen.ts +16 -33
- package/src/templates/default/app/hooks/use-navigation-state.ts +13 -3
- package/src/templates/default/app/lib/tab-id.ts +1 -0
- package/src/templates/default/app/root.tsx +2 -1
- package/src/templates/default/app/routes/_index.tsx +11 -0
- package/src/templates/default/package.json +2 -1
- package/src/templates/workspace-core/.agents/skills/real-time-sync/SKILL.md +9 -1
- package/src/templates/workspace-core/AGENTS.md +8 -0
- package/src/templates/workspace-root/AGENTS.md +7 -0
- package/dist/templates/default/server/routes/api/hello.get.ts +0 -5
- package/dist/templates/default/shared/api.ts +0 -6
- package/src/templates/default/server/routes/api/hello.get.ts +0 -5
- package/src/templates/default/shared/api.ts +0 -6
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
export declare const MCP_OAUTH_SCOPES: readonly ["mcp:read", "mcp:write", "mcp:apps"];
|
|
2
|
+
export declare const MCP_OAUTH_DEFAULT_SCOPE: string;
|
|
3
|
+
export interface McpOAuthAccessTokenClaims {
|
|
4
|
+
sub: string;
|
|
5
|
+
org_domain?: string;
|
|
6
|
+
scope: string;
|
|
7
|
+
client_id: string;
|
|
8
|
+
resource: string;
|
|
9
|
+
typ: "agent-native-mcp-oauth";
|
|
10
|
+
}
|
|
11
|
+
export declare function normalizeOAuthScope(input: unknown): string | null;
|
|
12
|
+
export declare function scopeList(scope: string | undefined): string[];
|
|
13
|
+
export declare function hasMcpOAuthScope(scopes: string[] | undefined, scope: (typeof MCP_OAUTH_SCOPES)[number]): boolean;
|
|
14
|
+
export declare function signMcpOAuthAccessToken(params: {
|
|
15
|
+
ownerEmail: string;
|
|
16
|
+
orgDomain?: string | null;
|
|
17
|
+
clientId: string;
|
|
18
|
+
scope: string;
|
|
19
|
+
resource: string;
|
|
20
|
+
issuer: string;
|
|
21
|
+
}): Promise<string>;
|
|
22
|
+
export declare function verifyMcpOAuthAccessToken(token: string, resource: string | undefined): Promise<{
|
|
23
|
+
userEmail: string;
|
|
24
|
+
orgDomain?: string;
|
|
25
|
+
scopes: string[];
|
|
26
|
+
clientId: string;
|
|
27
|
+
} | null>;
|
|
28
|
+
//# sourceMappingURL=oauth-token.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"oauth-token.d.ts","sourceRoot":"","sources":["../../src/mcp/oauth-token.ts"],"names":[],"mappings":"AAKA,eAAO,MAAM,gBAAgB,gDAAiD,CAAC;AAE/E,eAAO,MAAM,uBAAuB,QAA6B,CAAC;AAElE,MAAM,WAAW,yBAAyB;IACxC,GAAG,EAAE,MAAM,CAAC;IACZ,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,KAAK,EAAE,MAAM,CAAC;IACd,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC;IACjB,GAAG,EAAE,wBAAwB,CAAC;CAC/B;AAMD,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,GAAG,IAAI,CAYjE;AAED,wBAAgB,SAAS,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,EAAE,CAK7D;AAED,wBAAgB,gBAAgB,CAC9B,MAAM,EAAE,MAAM,EAAE,GAAG,SAAS,EAC5B,KAAK,EAAE,CAAC,OAAO,gBAAgB,CAAC,CAAC,MAAM,CAAC,GACvC,OAAO,CAGT;AAED,wBAAsB,uBAAuB,CAAC,MAAM,EAAE;IACpD,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,MAAM,CAAC;CAChB,GAAG,OAAO,CAAC,MAAM,CAAC,CAgBlB;AAED,wBAAsB,yBAAyB,CAC7C,KAAK,EAAE,MAAM,EACb,QAAQ,EAAE,MAAM,GAAG,SAAS,GAC3B,OAAO,CAAC;IACT,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,MAAM,EAAE,MAAM,EAAE,CAAC;IACjB,QAAQ,EAAE,MAAM,CAAC;CAClB,GAAG,IAAI,CAAC,CA2BR"}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import * as jose from "jose";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { getAuthSecret } from "../server/better-auth-instance.js";
|
|
4
|
+
import { MCP_OAUTH_ACCESS_TOKEN_TTL } from "./oauth-store.js";
|
|
5
|
+
export const MCP_OAUTH_SCOPES = ["mcp:read", "mcp:write", "mcp:apps"];
|
|
6
|
+
export const MCP_OAUTH_DEFAULT_SCOPE = MCP_OAUTH_SCOPES.join(" ");
|
|
7
|
+
function signingSecret() {
|
|
8
|
+
return new TextEncoder().encode(process.env.A2A_SECRET || getAuthSecret());
|
|
9
|
+
}
|
|
10
|
+
export function normalizeOAuthScope(input) {
|
|
11
|
+
const requested = typeof input === "string"
|
|
12
|
+
? input
|
|
13
|
+
.split(/\s+/)
|
|
14
|
+
.map((s) => s.trim())
|
|
15
|
+
.filter(Boolean)
|
|
16
|
+
: [];
|
|
17
|
+
const allowed = new Set(MCP_OAUTH_SCOPES);
|
|
18
|
+
if (requested.length === 0)
|
|
19
|
+
return MCP_OAUTH_DEFAULT_SCOPE;
|
|
20
|
+
const selected = requested.filter((scope) => allowed.has(scope));
|
|
21
|
+
return selected.length ? [...new Set(selected)].join(" ") : null;
|
|
22
|
+
}
|
|
23
|
+
export function scopeList(scope) {
|
|
24
|
+
return (scope ?? "")
|
|
25
|
+
.split(/\s+/)
|
|
26
|
+
.map((s) => s.trim())
|
|
27
|
+
.filter(Boolean);
|
|
28
|
+
}
|
|
29
|
+
export function hasMcpOAuthScope(scopes, scope) {
|
|
30
|
+
if (!scopes)
|
|
31
|
+
return true;
|
|
32
|
+
return scopes.includes(scope);
|
|
33
|
+
}
|
|
34
|
+
export async function signMcpOAuthAccessToken(params) {
|
|
35
|
+
return new jose.SignJWT({
|
|
36
|
+
typ: "agent-native-mcp-oauth",
|
|
37
|
+
sub: params.ownerEmail,
|
|
38
|
+
...(params.orgDomain ? { org_domain: params.orgDomain } : {}),
|
|
39
|
+
scope: params.scope,
|
|
40
|
+
client_id: params.clientId,
|
|
41
|
+
resource: params.resource,
|
|
42
|
+
})
|
|
43
|
+
.setProtectedHeader({ alg: "HS256" })
|
|
44
|
+
.setIssuer(params.issuer)
|
|
45
|
+
.setAudience(params.resource)
|
|
46
|
+
.setJti(randomUUID())
|
|
47
|
+
.setIssuedAt()
|
|
48
|
+
.setExpirationTime(MCP_OAUTH_ACCESS_TOKEN_TTL)
|
|
49
|
+
.sign(signingSecret());
|
|
50
|
+
}
|
|
51
|
+
export async function verifyMcpOAuthAccessToken(token, resource) {
|
|
52
|
+
if (!resource)
|
|
53
|
+
return null;
|
|
54
|
+
try {
|
|
55
|
+
const { payload } = await jose.jwtVerify(token, signingSecret(), {
|
|
56
|
+
audience: resource,
|
|
57
|
+
});
|
|
58
|
+
if (payload.typ !== "agent-native-mcp-oauth")
|
|
59
|
+
return null;
|
|
60
|
+
if (payload.resource !== resource)
|
|
61
|
+
return null;
|
|
62
|
+
if (typeof payload.sub !== "string" || !payload.sub)
|
|
63
|
+
return null;
|
|
64
|
+
if (typeof payload.client_id !== "string" || !payload.client_id) {
|
|
65
|
+
return null;
|
|
66
|
+
}
|
|
67
|
+
const scope = typeof payload.scope === "string" ? payload.scope : "";
|
|
68
|
+
const scopes = scopeList(scope);
|
|
69
|
+
if (!scopes.some((s) => MCP_OAUTH_SCOPES.includes(s))) {
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
return {
|
|
73
|
+
userEmail: payload.sub,
|
|
74
|
+
orgDomain: typeof payload.org_domain === "string" ? payload.org_domain : undefined,
|
|
75
|
+
scopes,
|
|
76
|
+
clientId: payload.client_id,
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
catch {
|
|
80
|
+
return null;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
//# sourceMappingURL=oauth-token.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"oauth-token.js","sourceRoot":"","sources":["../../src/mcp/oauth-token.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAC7B,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,aAAa,EAAE,MAAM,mCAAmC,CAAC;AAClE,OAAO,EAAE,0BAA0B,EAAE,MAAM,kBAAkB,CAAC;AAE9D,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,UAAU,EAAE,WAAW,EAAE,UAAU,CAAU,CAAC;AAE/E,MAAM,CAAC,MAAM,uBAAuB,GAAG,gBAAgB,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAWlE,SAAS,aAAa;IACpB,OAAO,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,UAAU,IAAI,aAAa,EAAE,CAAC,CAAC;AAC7E,CAAC;AAED,MAAM,UAAU,mBAAmB,CAAC,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AAK,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC;QACrE,MAAM,MAAM,GAAG,SAAS,CAAC,KAAK,CAAC,CAAC;QAChC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,gBAAgB,CAAC,QAAQ,CAAC,CAAQ,CAAC,CAAC,EAAE,CAAC;YAC7D,OAAO,IAAI,CAAC;QACd,CAAC;QACD,OAAO;YACL,SAAS,EAAE,OAAO,CAAC,GAAG;YACtB,SAAS,EACP,OAAO,OAAO,CAAC,UAAU,KAAK,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,SAAS;YACzE,MAAM;YACN,QAAQ,EAAE,OAAO,CAAC,SAAS;SAC5B,CAAC;IACJ,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import * as jose from \"jose\";\nimport { randomUUID } from \"node:crypto\";\nimport { getAuthSecret } from \"../server/better-auth-instance.js\";\nimport { MCP_OAUTH_ACCESS_TOKEN_TTL } from \"./oauth-store.js\";\n\nexport const MCP_OAUTH_SCOPES = [\"mcp:read\", \"mcp:write\", \"mcp:apps\"] as const;\n\nexport const MCP_OAUTH_DEFAULT_SCOPE = MCP_OAUTH_SCOPES.join(\" \");\n\nexport interface McpOAuthAccessTokenClaims {\n sub: string;\n org_domain?: string;\n scope: string;\n client_id: string;\n resource: string;\n typ: \"agent-native-mcp-oauth\";\n}\n\nfunction signingSecret(): Uint8Array {\n return new TextEncoder().encode(process.env.A2A_SECRET || getAuthSecret());\n}\n\nexport function normalizeOAuthScope(input: unknown): string | null {\n const requested =\n typeof input === \"string\"\n ? input\n .split(/\\s+/)\n .map((s) => s.trim())\n .filter(Boolean)\n : [];\n const allowed = new Set<string>(MCP_OAUTH_SCOPES);\n if (requested.length === 0) return MCP_OAUTH_DEFAULT_SCOPE;\n const selected = requested.filter((scope) => allowed.has(scope));\n return selected.length ? [...new Set(selected)].join(\" \") : null;\n}\n\nexport function scopeList(scope: string | undefined): string[] {\n return (scope ?? \"\")\n .split(/\\s+/)\n .map((s) => s.trim())\n .filter(Boolean);\n}\n\nexport function hasMcpOAuthScope(\n scopes: string[] | undefined,\n scope: (typeof MCP_OAUTH_SCOPES)[number],\n): boolean {\n if (!scopes) return true;\n return scopes.includes(scope);\n}\n\nexport async function signMcpOAuthAccessToken(params: {\n ownerEmail: string;\n orgDomain?: string | null;\n clientId: string;\n scope: string;\n resource: string;\n issuer: string;\n}): Promise<string> {\n return new jose.SignJWT({\n typ: \"agent-native-mcp-oauth\",\n sub: params.ownerEmail,\n ...(params.orgDomain ? { org_domain: params.orgDomain } : {}),\n scope: params.scope,\n client_id: params.clientId,\n resource: params.resource,\n })\n .setProtectedHeader({ alg: \"HS256\" })\n .setIssuer(params.issuer)\n .setAudience(params.resource)\n .setJti(randomUUID())\n .setIssuedAt()\n .setExpirationTime(MCP_OAUTH_ACCESS_TOKEN_TTL)\n .sign(signingSecret());\n}\n\nexport async function verifyMcpOAuthAccessToken(\n token: string,\n resource: string | undefined,\n): Promise<{\n userEmail: string;\n orgDomain?: string;\n scopes: string[];\n clientId: string;\n} | null> {\n if (!resource) return null;\n try {\n const { payload } = await jose.jwtVerify(token, signingSecret(), {\n audience: resource,\n });\n if (payload.typ !== \"agent-native-mcp-oauth\") return null;\n if (payload.resource !== resource) return null;\n if (typeof payload.sub !== \"string\" || !payload.sub) return null;\n if (typeof payload.client_id !== \"string\" || !payload.client_id) {\n return null;\n }\n const scope = typeof payload.scope === \"string\" ? payload.scope : \"\";\n const scopes = scopeList(scope);\n if (!scopes.some((s) => MCP_OAUTH_SCOPES.includes(s as any))) {\n return null;\n }\n return {\n userEmail: payload.sub,\n orgDomain:\n typeof payload.org_domain === \"string\" ? payload.org_domain : undefined,\n scopes,\n clientId: payload.client_id,\n };\n } catch {\n return null;\n }\n}\n"]}
|
package/dist/mcp/server.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../../src/mcp/server.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,IAAI,CAAC;
|
|
1
|
+
{"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../../src/mcp/server.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,IAAI,CAAC;AAWlC,OAAO,EACL,yBAAyB,EACzB,UAAU,EACV,eAAe,EACf,sBAAsB,EACtB,kBAAkB,EAClB,KAAK,SAAS,EACd,KAAK,iBAAiB,EACtB,KAAK,cAAc,EACpB,MAAM,mBAAmB,CAAC;AAM3B,OAAO,EACL,yBAAyB,EACzB,UAAU,EACV,eAAe,EACf,sBAAsB,EACtB,kBAAkB,GACnB,CAAC;AACF,YAAY,EAAE,SAAS,EAAE,iBAAiB,EAAE,cAAc,EAAE,CAAC;AA2G7D;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wBAAsB,gBAAgB,CACpC,KAAK,EAAE,OAAO,EACd,MAAM,EAAE,SAAS,GAChB,OAAO,CAAC,QAAQ,GAAG,MAAM,GAAG;IAAE,KAAK,EAAE,MAAM,CAAA;CAAE,GAAG,SAAS,CAAC,CA2H5D;AAMD;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,QAAQ,CACtB,QAAQ,EAAE,GAAG,EACb,MAAM,EAAE,SAAS,EACjB,WAAW,SAAmB,GAC7B,IAAI,CAYN"}
|
package/dist/mcp/server.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { getH3App } from "../server/framework-request-handler.js";
|
|
2
|
-
import { defineEventHandler, setResponseStatus, getMethod, getRequestHeader, } from "h3";
|
|
2
|
+
import { defineEventHandler, setResponseStatus, setResponseHeader, getMethod, getRequestHeader, } from "h3";
|
|
3
3
|
import { readBody } from "../server/h3-helpers.js";
|
|
4
4
|
import { isLoopbackRequest } from "../server/auth.js";
|
|
5
5
|
import { createMCPServerForRequest, verifyAuth, getAccessTokens, resolveOrgIdFromDomain, buildLinkArtifacts, } from "./build-server.js";
|
|
6
|
+
import { buildMcpOAuthChallenge, getMcpOAuthResource } from "./oauth-route.js";
|
|
6
7
|
// Re-export the shared MCP server builder + types so the stdio transport and
|
|
7
8
|
// any (future) external importer of `@agent-native/core/mcp` keep resolving
|
|
8
9
|
// against `./server.js` exactly as before this refactor.
|
|
@@ -146,11 +147,14 @@ export async function handleMcpRequest(event, config) {
|
|
|
146
147
|
// `Host: localhost`). A deployed app missing A2A_SECRET / ACCESS_TOKEN
|
|
147
148
|
// must fail closed rather than trust a spoofable owner-email header that
|
|
148
149
|
// `fullSurface` would otherwise escalate to the full mutating surface.
|
|
150
|
+
const requestMeta = deriveRequestMeta(event);
|
|
149
151
|
const authResult = await verifyAuth(authHeader, ownerEmailHeader, {
|
|
150
152
|
allowDevOpen: isLoopbackRequest(event),
|
|
153
|
+
resourceUrl: getMcpOAuthResource(event),
|
|
151
154
|
});
|
|
152
155
|
if (!authResult.authed) {
|
|
153
156
|
setResponseStatus(event, 401);
|
|
157
|
+
setResponseHeader(event, "WWW-Authenticate", buildMcpOAuthChallenge(event));
|
|
154
158
|
return { error: "Unauthorized" };
|
|
155
159
|
}
|
|
156
160
|
// Stateless mode: only POST is meaningful
|
|
@@ -172,7 +176,6 @@ export async function handleMcpRequest(event, config) {
|
|
|
172
176
|
// connected real caller (connect-minted token / `mcp install` /
|
|
173
177
|
// ACCESS_TOKEN / production) gets the full action surface even in local
|
|
174
178
|
// dev; unauthenticated dev probes stay sparse. See `external-agents` skill.
|
|
175
|
-
const requestMeta = deriveRequestMeta(event);
|
|
176
179
|
const server = await createMCPServerForRequest(config, authResult.identity, {
|
|
177
180
|
...requestMeta,
|
|
178
181
|
fullSurface: authResult.fullSurface === true,
|
package/dist/mcp/server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
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AAG,CACT,+BAA+B,WAAW,SAAS,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,MAAM,SAAS,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,EAAE,GAAG,CACvI,CAAC;AACN,CAAC","sourcesContent":["import type { H3Event } from \"h3\";\nimport { getH3App } from \"../server/framework-request-handler.js\";\nimport {\n defineEventHandler,\n setResponseStatus,\n getMethod,\n getRequestHeader,\n} from \"h3\";\nimport { readBody } from \"../server/h3-helpers.js\";\nimport { isLoopbackRequest } from \"../server/auth.js\";\nimport {\n createMCPServerForRequest,\n verifyAuth,\n getAccessTokens,\n resolveOrgIdFromDomain,\n buildLinkArtifacts,\n type MCPConfig,\n type MCPCallerIdentity,\n type MCPRequestMeta,\n} from \"./build-server.js\";\n\n// Re-export the shared MCP server builder + types so the stdio transport and\n// any (future) external importer of `@agent-native/core/mcp` keep resolving\n// against `./server.js` exactly as before this refactor.\nexport {\n createMCPServerForRequest,\n verifyAuth,\n getAccessTokens,\n resolveOrgIdFromDomain,\n buildLinkArtifacts,\n};\nexport type { MCPConfig, MCPCallerIdentity, MCPRequestMeta };\n\n// ---------------------------------------------------------------------------\n// Runtime detection — Node fast-path vs. web-standard fallback\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve the underlying Node `http` req/res pair if (and only if) we're\n * running on a real Node HTTP server (local dev, `node` Nitro preset). On the\n * web-standard runtime (Nitro 3 / Netlify web runtime, Cloudflare, Deno, Bun)\n * BOTH of these are undefined — that's the signal to take the web fallback\n * instead of returning 501.\n */\nfunction getNodeReqRes(event: H3Event): {\n nodeReq: any | undefined;\n nodeRes: any | undefined;\n} {\n const e = event as any;\n const nodeReq = e.node?.req ?? e.req?.runtime?.node?.req;\n const nodeRes = e.node?.res ?? e.req?.runtime?.node?.res;\n return { nodeReq, nodeRes };\n}\n\n/**\n * Derive the request origin + the markdown deep-link target from the inbound\n * headers. Identical logic for both the Node and web paths so the absolute\n * deep-link URLs in tool results are computed the same way regardless of\n * runtime.\n */\nfunction deriveRequestMeta(event: H3Event): MCPRequestMeta {\n const forwardedProto = getRequestHeader(event, \"x-forwarded-proto\");\n const host = getRequestHeader(event, \"host\");\n const proto =\n forwardedProto?.split(\",\")[0]?.trim() ||\n (host && /^(localhost|127\\.0\\.0\\.1)(:|$)/.test(host) ? \"http\" : \"https\");\n const origin = host ? `${proto}://${host}` : undefined;\n const targetHeader = getRequestHeader(\n event,\n \"x-agent-native-open-target\",\n )?.toLowerCase();\n const target =\n targetHeader === \"desktop\" ||\n targetHeader === \"terminal\" ||\n targetHeader === \"browser\"\n ? (targetHeader as MCPRequestMeta[\"target\"])\n : undefined;\n return { origin, target };\n}\n\n/**\n * Reconstruct a Web Standard `Request` for the web-standard MCP transport.\n *\n * On the web runtime h3 v2 exposes the real web `Request` as `event.req`; we\n * prefer it (its `method` / `headers` are exactly what the client sent). But\n * the framework middleware rewrites `event.req.url` when it strips a mount\n * prefix, and the transport reads `req.method` + `req.headers` (never the\n * body — we pass that via `parsedBody`), so we always synthesize a clean\n * `Request` with the verified method + a fresh `Headers` copy. The URL is\n * cosmetic for the SDK (it only does `new URL(req.url)` for `requestInfo`),\n * so a best-effort absolute URL derived from the inbound host is sufficient\n * and never throws.\n */\nfunction buildWebRequest(event: H3Event, method: string): Request {\n const src = (event as any).req as Request | undefined;\n\n const headers = new Headers();\n if (src?.headers && typeof src.headers.forEach === \"function\") {\n src.headers.forEach((value, key) => headers.set(key, value));\n } else {\n const rawHeaders = (event as any).node?.req?.headers as\n | Record<string, string | string[] | undefined>\n | undefined;\n if (rawHeaders) {\n for (const [key, value] of Object.entries(rawHeaders)) {\n if (value == null) continue;\n headers.set(key, Array.isArray(value) ? value.join(\", \") : value);\n }\n }\n }\n\n // The SDK requires Accept + Content-Type to advertise both JSON and SSE on\n // a POST. Real MCP clients (Claude Code, `agent-native connect`) always\n // send these; we never inject/alter them — if they're absent the SDK\n // returns its spec-mandated 406/415, identical to the Node path.\n\n const host = headers.get(\"host\") || \"localhost\";\n const forwardedProto = headers.get(\"x-forwarded-proto\");\n const proto =\n forwardedProto?.split(\",\")[0]?.trim() ||\n (/^(localhost|127\\.0\\.0\\.1)(:|$)/.test(host) ? \"http\" : \"https\");\n let url = `${proto}://${host}/_agent-native/mcp`;\n try {\n if (src?.url) url = new URL(src.url).href;\n } catch {\n // keep the synthesized URL\n }\n\n // No body here on purpose: the JSON-RPC payload is forwarded via the\n // transport's `parsedBody` option (the same mechanism the Node transport\n // uses), so the request stream is never read twice.\n return new Request(url, { method, headers });\n}\n\n// ---------------------------------------------------------------------------\n// handleMcpRequest — runtime-agnostic MCP request handler\n// ---------------------------------------------------------------------------\n\n/**\n * Handle a single `{routePrefix}/mcp` request on either runtime.\n *\n * - **Node fast-path** (real Node HTTP server): unchanged — delegate to the\n * SDK's `StreamableHTTPServerTransport.handleRequest(nodeReq, nodeRes,\n * body)`, which writes directly to the Node response (full protocol incl.\n * SSE).\n * - **Web-standard fallback** (Nitro 3 / Netlify web runtime, Cloudflare,\n * Deno, Bun — where there is no Node req/res): build the SAME MCP `Server`\n * from the SAME config + identity, drive it through the SDK's\n * `WebStandardStreamableHTTPServerTransport` (which the Node transport is\n * itself just a thin wrapper around), and return the resulting Web\n * `Response` as a normal h3 return value.\n *\n * Auth, the `runWithRequestContext` identity wrap, the deep-link `_meta` /\n * markdown append, `requestMeta` origin/target derivation and the stateless\n * semantics are IDENTICAL on both paths because both build the same server\n * via `createMCPServerForRequest` and both transports funnel into the same\n * `WebStandardStreamableHTTPServerTransport.handleRequest(webRequest, {\n * parsedBody })` with the same options.\n *\n * Returns:\n * - `undefined` when the request targets a sub-route (so management/status\n * routes mounted under `/_agent-native/mcp/*` handle it themselves) — the\n * h3 mount falls through to the next handler.\n * - a Web `Response` (web fallback) or a string/object (Node path /\n * auth-error path) otherwise. The Node path also sets `_handled` so h3\n * doesn't double-write.\n */\nexport async function handleMcpRequest(\n event: H3Event,\n config: MCPConfig,\n): Promise<Response | string | { error: string } | undefined> {\n const pathname = event.url?.pathname || \"/\";\n const subpath = pathname.replace(/^\\/+/, \"\").replace(/\\/+$/, \"\");\n if (subpath) {\n // Let management/status routes mounted under /_agent-native/mcp/* handle\n // their own requests instead of treating them as MCP protocol traffic.\n return undefined;\n }\n\n const method = getMethod(event);\n\n // Auth check — extracts the caller's identity from the JWT (`sub`), or, on\n // the static-token / dev-open path, from the forwarded\n // `X-Agent-Native-Owner-Email` hint the stdio proxy sends (the\n // `agent-native mcp install` flow). Without this the install flow would run\n // every tool unscoped (userEmail === undefined).\n const authHeader = getRequestHeader(event, \"authorization\");\n const ownerEmailHeader = getRequestHeader(\n event,\n \"x-agent-native-owner-email\",\n );\n // Gate header-only dev-open on the REAL socket peer, never a parsed\n // `Host` header (client-controlled — an attacker could send\n // `Host: localhost`). A deployed app missing A2A_SECRET / ACCESS_TOKEN\n // must fail closed rather than trust a spoofable owner-email header that\n // `fullSurface` would otherwise escalate to the full mutating surface.\n const authResult = await verifyAuth(authHeader, ownerEmailHeader, {\n allowDevOpen: isLoopbackRequest(event),\n });\n if (!authResult.authed) {\n setResponseStatus(event, 401);\n return { error: \"Unauthorized\" };\n }\n\n // Stateless mode: only POST is meaningful\n if (method === \"DELETE\") {\n setResponseStatus(event, 204);\n return \"\";\n }\n\n if (method !== \"POST\" && method !== \"GET\") {\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }\n\n // Read body for POST (GET has no body). Read it via the h3 helper exactly\n // once; both transports accept it as a pre-parsed body so the request\n // stream is never consumed twice.\n const body = method === \"POST\" ? await readBody(event) : undefined;\n\n // Per-request stateless transport + server. Both runtimes build the SAME\n // server from the SAME config + verified identity + request meta, so\n // tools/list, tools/call, and the deep-link `_meta` are identical. A\n // connected real caller (connect-minted token / `mcp install` /\n // ACCESS_TOKEN / production) gets the full action surface even in local\n // dev; unauthenticated dev probes stay sparse. See `external-agents` skill.\n const requestMeta = deriveRequestMeta(event);\n const server = await createMCPServerForRequest(config, authResult.identity, {\n ...requestMeta,\n fullSurface: authResult.fullSurface === true,\n });\n\n const { nodeReq, nodeRes } = getNodeReqRes(event);\n\n if (nodeReq && nodeRes) {\n // ---- Node fast-path (UNCHANGED behavior) --------------------------------\n const { StreamableHTTPServerTransport } =\n await import(\"@modelcontextprotocol/sdk/server/streamableHttp.js\");\n const transport = new StreamableHTTPServerTransport({\n sessionIdGenerator: undefined, // stateless\n });\n await server.connect(transport);\n try {\n // The SDK transport writes directly to the Node response. Node-only by\n // construction; we only reach here when real Node req/res exist.\n await transport.handleRequest(nodeReq, nodeRes, body);\n } catch (err: any) {\n // The SDK transport writes directly to the Node response. If the socket\n // is already closed/ended (client disconnected, or the host stream\n // layer also flushed), Node throws ERR_STREAM_WRITE_AFTER_END *after*\n // the MCP payload was already delivered correctly. Swallow that benign\n // post-flush write so an external agent disconnecting mid-stream can\n // never take down the server process; rethrow anything else.\n if (err?.code !== \"ERR_STREAM_WRITE_AFTER_END\") throw err;\n if (process.env.DEBUG)\n console.log(\n \"[mcp] ignored post-flush ERR_STREAM_WRITE_AFTER_END (client disconnected)\",\n );\n }\n // Prevent H3 from double-writing the response\n (event as any)._handled = true;\n return undefined;\n }\n\n // ---- Web-standard fallback (Nitro 3 / Netlify web runtime, CF, Deno,\n // Bun) ---------------------------------------------------------------------\n //\n // `StreamableHTTPServerTransport` is itself just a thin wrapper that\n // converts the Node req/res to a web Request/Response and delegates to\n // `WebStandardStreamableHTTPServerTransport.handleRequest(webRequest, {\n // parsedBody })`. Using the web transport directly with the SAME options +\n // the same pre-read `parsedBody` produces byte-identical protocol output\n // (including the deep-link `_meta` built inside createMCPServerForRequest),\n // and works on every web runtime because it returns a Web `Response`\n // (JSON for request/response, or an SSE `ReadableStream` body which h3\n // streams natively).\n const { WebStandardStreamableHTTPServerTransport } =\n await import(\"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js\");\n const transport = new WebStandardStreamableHTTPServerTransport({\n sessionIdGenerator: undefined, // stateless — same as the Node path\n });\n await server.connect(transport);\n const webRequest = buildWebRequest(event, method);\n // `parsedBody: undefined` would make the SDK try to read `req.json()`; our\n // synthesized request has no body, so only pass the option for POST (where\n // we actually have a parsed body). For GET the transport reads no body.\n const response = await transport.handleRequest(\n webRequest,\n method === \"POST\" ? { parsedBody: body } : undefined,\n );\n return response;\n}\n\n// ---------------------------------------------------------------------------\n// mountMCP — register MCP Streamable HTTP endpoint on H3/Nitro\n// ---------------------------------------------------------------------------\n\n/**\n * Mount an MCP remote server on an H3/Nitro app.\n *\n * Endpoint: `{routePrefix}/mcp` (default `/_agent-native/mcp`)\n *\n * Uses stateless Streamable HTTP transport — no in-memory sessions,\n * compatible with serverless deployments. Runtime-agnostic: a real Node\n * server uses the SDK's Node transport; the web-standard runtime (Nitro 3 /\n * Netlify web runtime, Cloudflare, Deno, Bun) uses the SDK's web-standard\n * transport. Both build the same server and produce identical JSON-RPC\n * output.\n *\n * Auth: Bearer token matching ACCESS_TOKEN/ACCESS_TOKENS or JWT via A2A_SECRET.\n * No auth required when neither is configured (dev mode).\n */\nexport function mountMCP(\n nitroApp: any,\n config: MCPConfig,\n routePrefix = \"/_agent-native\",\n): void {\n getH3App(nitroApp).use(\n `${routePrefix}/mcp`,\n defineEventHandler(async (event) => {\n return handleMcpRequest(event as H3Event, config);\n }),\n );\n\n if (process.env.DEBUG)\n console.log(\n `[mcp] Mounted MCP server at ${routePrefix}/mcp (${Object.keys(config.actions).length} tools${config.askAgent ? \" + ask-agent\" : \"\"})`,\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/mcp/server.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,wCAAwC,CAAC;AAClE,OAAO,EACL,kBAAkB,EAClB,iBAAiB,EACjB,iBAAiB,EACjB,SAAS,EACT,gBAAgB,GACjB,MAAM,IAAI,CAAC;AACZ,OAAO,EAAE,QAAQ,EAAE,MAAM,yBAAyB,CAAC;AACnD,O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C,OAAO,CAAC,CAAC,MAAM,SAAS,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,EAAE,GAAG,CACvI,CAAC;AACN,CAAC","sourcesContent":["import type { H3Event } from \"h3\";\nimport { getH3App } from \"../server/framework-request-handler.js\";\nimport {\n defineEventHandler,\n setResponseStatus,\n setResponseHeader,\n getMethod,\n getRequestHeader,\n} from \"h3\";\nimport { readBody } from \"../server/h3-helpers.js\";\nimport { isLoopbackRequest } from \"../server/auth.js\";\nimport {\n createMCPServerForRequest,\n verifyAuth,\n getAccessTokens,\n resolveOrgIdFromDomain,\n buildLinkArtifacts,\n type MCPConfig,\n type MCPCallerIdentity,\n type MCPRequestMeta,\n} from \"./build-server.js\";\nimport { buildMcpOAuthChallenge, getMcpOAuthResource } from \"./oauth-route.js\";\n\n// Re-export the shared MCP server builder + types so the stdio transport and\n// any (future) external importer of `@agent-native/core/mcp` keep resolving\n// against `./server.js` exactly as before this refactor.\nexport {\n createMCPServerForRequest,\n verifyAuth,\n getAccessTokens,\n resolveOrgIdFromDomain,\n buildLinkArtifacts,\n};\nexport type { MCPConfig, MCPCallerIdentity, MCPRequestMeta };\n\n// ---------------------------------------------------------------------------\n// Runtime detection — Node fast-path vs. web-standard fallback\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve the underlying Node `http` req/res pair if (and only if) we're\n * running on a real Node HTTP server (local dev, `node` Nitro preset). On the\n * web-standard runtime (Nitro 3 / Netlify web runtime, Cloudflare, Deno, Bun)\n * BOTH of these are undefined — that's the signal to take the web fallback\n * instead of returning 501.\n */\nfunction getNodeReqRes(event: H3Event): {\n nodeReq: any | undefined;\n nodeRes: any | undefined;\n} {\n const e = event as any;\n const nodeReq = e.node?.req ?? e.req?.runtime?.node?.req;\n const nodeRes = e.node?.res ?? e.req?.runtime?.node?.res;\n return { nodeReq, nodeRes };\n}\n\n/**\n * Derive the request origin + the markdown deep-link target from the inbound\n * headers. Identical logic for both the Node and web paths so the absolute\n * deep-link URLs in tool results are computed the same way regardless of\n * runtime.\n */\nfunction deriveRequestMeta(event: H3Event): MCPRequestMeta {\n const forwardedProto = getRequestHeader(event, \"x-forwarded-proto\");\n const host = getRequestHeader(event, \"host\");\n const proto =\n forwardedProto?.split(\",\")[0]?.trim() ||\n (host && /^(localhost|127\\.0\\.0\\.1)(:|$)/.test(host) ? \"http\" : \"https\");\n const origin = host ? `${proto}://${host}` : undefined;\n const targetHeader = getRequestHeader(\n event,\n \"x-agent-native-open-target\",\n )?.toLowerCase();\n const target =\n targetHeader === \"desktop\" ||\n targetHeader === \"terminal\" ||\n targetHeader === \"browser\"\n ? (targetHeader as MCPRequestMeta[\"target\"])\n : undefined;\n return { origin, target };\n}\n\n/**\n * Reconstruct a Web Standard `Request` for the web-standard MCP transport.\n *\n * On the web runtime h3 v2 exposes the real web `Request` as `event.req`; we\n * prefer it (its `method` / `headers` are exactly what the client sent). But\n * the framework middleware rewrites `event.req.url` when it strips a mount\n * prefix, and the transport reads `req.method` + `req.headers` (never the\n * body — we pass that via `parsedBody`), so we always synthesize a clean\n * `Request` with the verified method + a fresh `Headers` copy. The URL is\n * cosmetic for the SDK (it only does `new URL(req.url)` for `requestInfo`),\n * so a best-effort absolute URL derived from the inbound host is sufficient\n * and never throws.\n */\nfunction buildWebRequest(event: H3Event, method: string): Request {\n const src = (event as any).req as Request | undefined;\n\n const headers = new Headers();\n if (src?.headers && typeof src.headers.forEach === \"function\") {\n src.headers.forEach((value, key) => headers.set(key, value));\n } else {\n const rawHeaders = (event as any).node?.req?.headers as\n | Record<string, string | string[] | undefined>\n | undefined;\n if (rawHeaders) {\n for (const [key, value] of Object.entries(rawHeaders)) {\n if (value == null) continue;\n headers.set(key, Array.isArray(value) ? value.join(\", \") : value);\n }\n }\n }\n\n // The SDK requires Accept + Content-Type to advertise both JSON and SSE on\n // a POST. Real MCP clients (Claude Code, `agent-native connect`) always\n // send these; we never inject/alter them — if they're absent the SDK\n // returns its spec-mandated 406/415, identical to the Node path.\n\n const host = headers.get(\"host\") || \"localhost\";\n const forwardedProto = headers.get(\"x-forwarded-proto\");\n const proto =\n forwardedProto?.split(\",\")[0]?.trim() ||\n (/^(localhost|127\\.0\\.0\\.1)(:|$)/.test(host) ? \"http\" : \"https\");\n let url = `${proto}://${host}/_agent-native/mcp`;\n try {\n if (src?.url) url = new URL(src.url).href;\n } catch {\n // keep the synthesized URL\n }\n\n // No body here on purpose: the JSON-RPC payload is forwarded via the\n // transport's `parsedBody` option (the same mechanism the Node transport\n // uses), so the request stream is never read twice.\n return new Request(url, { method, headers });\n}\n\n// ---------------------------------------------------------------------------\n// handleMcpRequest — runtime-agnostic MCP request handler\n// ---------------------------------------------------------------------------\n\n/**\n * Handle a single `{routePrefix}/mcp` request on either runtime.\n *\n * - **Node fast-path** (real Node HTTP server): unchanged — delegate to the\n * SDK's `StreamableHTTPServerTransport.handleRequest(nodeReq, nodeRes,\n * body)`, which writes directly to the Node response (full protocol incl.\n * SSE).\n * - **Web-standard fallback** (Nitro 3 / Netlify web runtime, Cloudflare,\n * Deno, Bun — where there is no Node req/res): build the SAME MCP `Server`\n * from the SAME config + identity, drive it through the SDK's\n * `WebStandardStreamableHTTPServerTransport` (which the Node transport is\n * itself just a thin wrapper around), and return the resulting Web\n * `Response` as a normal h3 return value.\n *\n * Auth, the `runWithRequestContext` identity wrap, the deep-link `_meta` /\n * markdown append, `requestMeta` origin/target derivation and the stateless\n * semantics are IDENTICAL on both paths because both build the same server\n * via `createMCPServerForRequest` and both transports funnel into the same\n * `WebStandardStreamableHTTPServerTransport.handleRequest(webRequest, {\n * parsedBody })` with the same options.\n *\n * Returns:\n * - `undefined` when the request targets a sub-route (so management/status\n * routes mounted under `/_agent-native/mcp/*` handle it themselves) — the\n * h3 mount falls through to the next handler.\n * - a Web `Response` (web fallback) or a string/object (Node path /\n * auth-error path) otherwise. The Node path also sets `_handled` so h3\n * doesn't double-write.\n */\nexport async function handleMcpRequest(\n event: H3Event,\n config: MCPConfig,\n): Promise<Response | string | { error: string } | undefined> {\n const pathname = event.url?.pathname || \"/\";\n const subpath = pathname.replace(/^\\/+/, \"\").replace(/\\/+$/, \"\");\n if (subpath) {\n // Let management/status routes mounted under /_agent-native/mcp/* handle\n // their own requests instead of treating them as MCP protocol traffic.\n return undefined;\n }\n\n const method = getMethod(event);\n\n // Auth check — extracts the caller's identity from the JWT (`sub`), or, on\n // the static-token / dev-open path, from the forwarded\n // `X-Agent-Native-Owner-Email` hint the stdio proxy sends (the\n // `agent-native mcp install` flow). Without this the install flow would run\n // every tool unscoped (userEmail === undefined).\n const authHeader = getRequestHeader(event, \"authorization\");\n const ownerEmailHeader = getRequestHeader(\n event,\n \"x-agent-native-owner-email\",\n );\n // Gate header-only dev-open on the REAL socket peer, never a parsed\n // `Host` header (client-controlled — an attacker could send\n // `Host: localhost`). A deployed app missing A2A_SECRET / ACCESS_TOKEN\n // must fail closed rather than trust a spoofable owner-email header that\n // `fullSurface` would otherwise escalate to the full mutating surface.\n const requestMeta = deriveRequestMeta(event);\n const authResult = await verifyAuth(authHeader, ownerEmailHeader, {\n allowDevOpen: isLoopbackRequest(event),\n resourceUrl: getMcpOAuthResource(event),\n });\n if (!authResult.authed) {\n setResponseStatus(event, 401);\n setResponseHeader(event, \"WWW-Authenticate\", buildMcpOAuthChallenge(event));\n return { error: \"Unauthorized\" };\n }\n\n // Stateless mode: only POST is meaningful\n if (method === \"DELETE\") {\n setResponseStatus(event, 204);\n return \"\";\n }\n\n if (method !== \"POST\" && method !== \"GET\") {\n setResponseStatus(event, 405);\n return { error: \"Method not allowed\" };\n }\n\n // Read body for POST (GET has no body). Read it via the h3 helper exactly\n // once; both transports accept it as a pre-parsed body so the request\n // stream is never consumed twice.\n const body = method === \"POST\" ? await readBody(event) : undefined;\n\n // Per-request stateless transport + server. Both runtimes build the SAME\n // server from the SAME config + verified identity + request meta, so\n // tools/list, tools/call, and the deep-link `_meta` are identical. A\n // connected real caller (connect-minted token / `mcp install` /\n // ACCESS_TOKEN / production) gets the full action surface even in local\n // dev; unauthenticated dev probes stay sparse. See `external-agents` skill.\n const server = await createMCPServerForRequest(config, authResult.identity, {\n ...requestMeta,\n fullSurface: authResult.fullSurface === true,\n });\n\n const { nodeReq, nodeRes } = getNodeReqRes(event);\n\n if (nodeReq && nodeRes) {\n // ---- Node fast-path (UNCHANGED behavior) --------------------------------\n const { StreamableHTTPServerTransport } =\n await import(\"@modelcontextprotocol/sdk/server/streamableHttp.js\");\n const transport = new StreamableHTTPServerTransport({\n sessionIdGenerator: undefined, // stateless\n });\n await server.connect(transport);\n try {\n // The SDK transport writes directly to the Node response. Node-only by\n // construction; we only reach here when real Node req/res exist.\n await transport.handleRequest(nodeReq, nodeRes, body);\n } catch (err: any) {\n // The SDK transport writes directly to the Node response. If the socket\n // is already closed/ended (client disconnected, or the host stream\n // layer also flushed), Node throws ERR_STREAM_WRITE_AFTER_END *after*\n // the MCP payload was already delivered correctly. Swallow that benign\n // post-flush write so an external agent disconnecting mid-stream can\n // never take down the server process; rethrow anything else.\n if (err?.code !== \"ERR_STREAM_WRITE_AFTER_END\") throw err;\n if (process.env.DEBUG)\n console.log(\n \"[mcp] ignored post-flush ERR_STREAM_WRITE_AFTER_END (client disconnected)\",\n );\n }\n // Prevent H3 from double-writing the response\n (event as any)._handled = true;\n return undefined;\n }\n\n // ---- Web-standard fallback (Nitro 3 / Netlify web runtime, CF, Deno,\n // Bun) ---------------------------------------------------------------------\n //\n // `StreamableHTTPServerTransport` is itself just a thin wrapper that\n // converts the Node req/res to a web Request/Response and delegates to\n // `WebStandardStreamableHTTPServerTransport.handleRequest(webRequest, {\n // parsedBody })`. Using the web transport directly with the SAME options +\n // the same pre-read `parsedBody` produces byte-identical protocol output\n // (including the deep-link `_meta` built inside createMCPServerForRequest),\n // and works on every web runtime because it returns a Web `Response`\n // (JSON for request/response, or an SSE `ReadableStream` body which h3\n // streams natively).\n const { WebStandardStreamableHTTPServerTransport } =\n await import(\"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js\");\n const transport = new WebStandardStreamableHTTPServerTransport({\n sessionIdGenerator: undefined, // stateless — same as the Node path\n });\n await server.connect(transport);\n const webRequest = buildWebRequest(event, method);\n // `parsedBody: undefined` would make the SDK try to read `req.json()`; our\n // synthesized request has no body, so only pass the option for POST (where\n // we actually have a parsed body). For GET the transport reads no body.\n const response = await transport.handleRequest(\n webRequest,\n method === \"POST\" ? { parsedBody: body } : undefined,\n );\n return response;\n}\n\n// ---------------------------------------------------------------------------\n// mountMCP — register MCP Streamable HTTP endpoint on H3/Nitro\n// ---------------------------------------------------------------------------\n\n/**\n * Mount an MCP remote server on an H3/Nitro app.\n *\n * Endpoint: `{routePrefix}/mcp` (default `/_agent-native/mcp`)\n *\n * Uses stateless Streamable HTTP transport — no in-memory sessions,\n * compatible with serverless deployments. Runtime-agnostic: a real Node\n * server uses the SDK's Node transport; the web-standard runtime (Nitro 3 /\n * Netlify web runtime, Cloudflare, Deno, Bun) uses the SDK's web-standard\n * transport. Both build the same server and produce identical JSON-RPC\n * output.\n *\n * Auth: Bearer token matching ACCESS_TOKEN/ACCESS_TOKENS or JWT via A2A_SECRET.\n * No auth required when neither is configured (dev mode).\n */\nexport function mountMCP(\n nitroApp: any,\n config: MCPConfig,\n routePrefix = \"/_agent-native\",\n): void {\n getH3App(nitroApp).use(\n `${routePrefix}/mcp`,\n defineEventHandler(async (event) => {\n return handleMcpRequest(event as H3Event, config);\n }),\n );\n\n if (process.env.DEBUG)\n console.log(\n `[mcp] Mounted MCP server at ${routePrefix}/mcp (${Object.keys(config.actions).length} tools${config.askAgent ? \" + ask-agent\" : \"\"})`,\n );\n}\n"]}
|
package/dist/mcp/stdio.d.ts
CHANGED
|
@@ -8,8 +8,8 @@
|
|
|
8
8
|
* - **proxy (default)** — connect an MCP `Client` over
|
|
9
9
|
* `StreamableHTTPClientTransport` to the *already-running* local app's
|
|
10
10
|
* `http://127.0.0.1:<port>/_agent-native/mcp`, and run a stdio `Server`
|
|
11
|
-
* that forwards
|
|
12
|
-
* single source of truth: HMR'd actions, the real registry, correct
|
|
11
|
+
* that forwards tools and optional MCP App resources to it. The live app
|
|
12
|
+
* is the single source of truth: HMR'd actions, the real registry, correct
|
|
13
13
|
* per-request deep links, and tenant scoping all come for free. If the
|
|
14
14
|
* app isn't running, we wait briefly for it (the workspace gateway boots
|
|
15
15
|
* it lazily on first request).
|
package/dist/mcp/stdio.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stdio.d.ts","sourceRoot":"","sources":["../../src/mcp/stdio.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;
|
|
1
|
+
{"version":3,"file":"stdio.d.ts","sourceRoot":"","sources":["../../src/mcp/stdio.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAKH,MAAM,WAAW,kBAAkB;IACjC,yEAAyE;IACzE,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,0EAA0E;IAC1E,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,qEAAqE;IACrE,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,qDAAqD;IACrD,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,qCAAqC;IACrC,GAAG,CAAC,EAAE,MAAM,CAAC,UAAU,CAAC;IACxB,sEAAsE;IACtE,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB;AAwOD;;;GAGG;AACH,wBAAsB,WAAW,CAC/B,IAAI,GAAE,kBAAuB,GAC5B,OAAO,CAAC,IAAI,CAAC,CAef"}
|
package/dist/mcp/stdio.js
CHANGED
|
@@ -8,8 +8,8 @@
|
|
|
8
8
|
* - **proxy (default)** — connect an MCP `Client` over
|
|
9
9
|
* `StreamableHTTPClientTransport` to the *already-running* local app's
|
|
10
10
|
* `http://127.0.0.1:<port>/_agent-native/mcp`, and run a stdio `Server`
|
|
11
|
-
* that forwards
|
|
12
|
-
* single source of truth: HMR'd actions, the real registry, correct
|
|
11
|
+
* that forwards tools and optional MCP App resources to it. The live app
|
|
12
|
+
* is the single source of truth: HMR'd actions, the real registry, correct
|
|
13
13
|
* per-request deep links, and tenant scoping all come for free. If the
|
|
14
14
|
* app isn't running, we wait briefly for it (the workspace gateway boots
|
|
15
15
|
* it lazily on first request).
|
|
@@ -61,10 +61,10 @@ async function probeOrigin(origin, timeoutMs = 800) {
|
|
|
61
61
|
/**
|
|
62
62
|
* Proxy mode: stdio Server ⇄ HTTP Client to the running app.
|
|
63
63
|
*
|
|
64
|
-
* We register the standard
|
|
65
|
-
*
|
|
66
|
-
*
|
|
67
|
-
*
|
|
64
|
+
* We register the standard handlers on the stdio server and forward them
|
|
65
|
+
* verbatim to the upstream HTTP MCP server via the SDK `Client`. The upstream
|
|
66
|
+
* owns tool definitions, results, MCP App resources, and the appended
|
|
67
|
+
* deep-link block / `_meta`, so nothing is duplicated here.
|
|
68
68
|
*/
|
|
69
69
|
async function runProxy(opts) {
|
|
70
70
|
const { origin, appId } = await resolveLocalAppOrigin({
|
|
@@ -96,7 +96,7 @@ async function runProxy(opts) {
|
|
|
96
96
|
const { StreamableHTTPClientTransport } = await import("@modelcontextprotocol/sdk/client/streamableHttp.js");
|
|
97
97
|
const { Server } = await import("@modelcontextprotocol/sdk/server/index.js");
|
|
98
98
|
const { StdioServerTransport } = await import("@modelcontextprotocol/sdk/server/stdio.js");
|
|
99
|
-
const { ListToolsRequestSchema, CallToolRequestSchema } = await import("@modelcontextprotocol/sdk/types.js");
|
|
99
|
+
const { ListToolsRequestSchema, CallToolRequestSchema, ListResourcesRequestSchema, ReadResourceRequestSchema, ListResourceTemplatesRequestSchema, } = await import("@modelcontextprotocol/sdk/types.js");
|
|
100
100
|
// --- Upstream HTTP client -------------------------------------------------
|
|
101
101
|
const clientTransport = new StreamableHTTPClientTransport(new URL(target), {
|
|
102
102
|
requestInit: { headers: authHeaders(env) },
|
|
@@ -105,7 +105,14 @@ async function runProxy(opts) {
|
|
|
105
105
|
await client.connect(clientTransport);
|
|
106
106
|
log(`Proxying stdio ⇄ ${target} (app: ${appId})`);
|
|
107
107
|
// --- Downstream stdio server ---------------------------------------------
|
|
108
|
-
const
|
|
108
|
+
const upstreamCapabilities = client.getServerCapabilities();
|
|
109
|
+
const capabilities = { tools: {} };
|
|
110
|
+
if (upstreamCapabilities?.resources)
|
|
111
|
+
capabilities.resources = {};
|
|
112
|
+
if (upstreamCapabilities?.extensions) {
|
|
113
|
+
capabilities.extensions = upstreamCapabilities.extensions;
|
|
114
|
+
}
|
|
115
|
+
const server = new Server({ name: `agent-native-${appId}`, version: "1.0.0" }, { capabilities });
|
|
109
116
|
server.setRequestHandler(ListToolsRequestSchema, async (request) => {
|
|
110
117
|
return client.listTools(request.params);
|
|
111
118
|
});
|
|
@@ -113,6 +120,17 @@ async function runProxy(opts) {
|
|
|
113
120
|
// Forward the call verbatim; the upstream appends the deep-link block.
|
|
114
121
|
return client.callTool(request.params);
|
|
115
122
|
});
|
|
123
|
+
if (upstreamCapabilities?.resources) {
|
|
124
|
+
server.setRequestHandler(ListResourcesRequestSchema, async (request) => {
|
|
125
|
+
return client.listResources(request.params);
|
|
126
|
+
});
|
|
127
|
+
server.setRequestHandler(ListResourceTemplatesRequestSchema, async (request) => {
|
|
128
|
+
return client.listResourceTemplates(request.params);
|
|
129
|
+
});
|
|
130
|
+
server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
|
|
131
|
+
return client.readResource(request.params);
|
|
132
|
+
});
|
|
133
|
+
}
|
|
116
134
|
const stdioTransport = new StdioServerTransport();
|
|
117
135
|
await server.connect(stdioTransport);
|
|
118
136
|
// Keep the proxy alive until the client/transport closes.
|
package/dist/mcp/stdio.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stdio.js","sourceRoot":"","sources":["../../src/mcp/stdio.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAEH,OAAO,EAAE,qBAAqB,EAAE,MAAM,w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;QACH,MAAM,QAAQ,CAAC,IAAI,CAAC,CAAC;IACvB,CAAC;IAAC,OAAO,GAAQ,EAAE,CAAC;QAClB,mEAAmE;QACnE,qEAAqE;QACrE,qEAAqE;QACrE,2CAA2C;QAC3C,GAAG,CAAC,sBAAsB,GAAG,EAAE,OAAO,IAAI,GAAG,EAAE,CAAC,CAAC;QACjD,MAAM,GAAG,CAAC;IACZ,CAAC;AACH,CAAC","sourcesContent":["/**\n * MCP **stdio** transport for the `agent-native mcp serve` command.\n *\n * This is the binary external coding agents (Claude Code, Claude Cowork,\n * Codex) actually launch — they speak MCP over a child process's stdio, not\n * HTTP. We expose the agent-native app's MCP surface over stdio in two modes:\n *\n * - **proxy (default)** — connect an MCP `Client` over\n * `StreamableHTTPClientTransport` to the *already-running* local app's\n * `http://127.0.0.1:<port>/_agent-native/mcp`, and run a stdio `Server`\n * that forwards `tools/list` + `tools/call` to it. The live app is the\n * single source of truth: HMR'd actions, the real registry, correct\n * per-request deep links, and tenant scoping all come for free. If the\n * app isn't running, we wait briefly for it (the workspace gateway boots\n * it lazily on first request).\n *\n * - **standalone (`--standalone`)** — no running server, no HMR. Build the\n * MCP server in-process from `autoDiscoverActions(cwd)` +\n * `createMCPServerForRequest`, connected straight to a\n * `StdioServerTransport`. Useful in CI / when nothing is serving.\n *\n * Node-only: imports `node:*` and the SDK stdio/http transports. Never part\n * of the serverless bundle.\n */\n\nimport { resolveLocalAppOrigin } from \"./workspace-resolve.js\";\n\nexport interface RunMCPStdioOptions {\n /** App id to bridge to (workspace). Optional in a single-app project. */\n appId?: string;\n /** Explicit port of the running app's dev server. Overrides discovery. */\n port?: number;\n /** Skip the HTTP proxy and build the server in-process from disk. */\n standalone?: boolean;\n /** Working directory (defaults to process.cwd()). */\n cwd?: string;\n /** Env (defaults to process.env). */\n env?: NodeJS.ProcessEnv;\n /** Max ms to wait for the running app before failing (proxy mode). */\n waitForAppMs?: number;\n}\n\nconst MCP_SUBPATH = \"/_agent-native/mcp\";\n\nfunction log(msg: string): void {\n // stderr only — stdout is the MCP protocol channel and must stay clean.\n process.stderr.write(`[mcp] ${msg}\\n`);\n}\n\n/**\n * Owner identity the installer wrote into the client config's env. Passed\n * through to the HTTP MCP endpoint as a JWT/identity bearer (when present)\n * so tool runs stay tenant-scoped. For local dev with a static ACCESS_TOKEN\n * the email is informational; for hosted JWT auth the token already carries\n * `sub`, so we only add an `X-Agent-Native-Owner-Email` hint header.\n */\nfunction authHeaders(env: NodeJS.ProcessEnv): Record<string, string> {\n const headers: Record<string, string> = {};\n const token = env.ACCESS_TOKEN || env.AGENT_NATIVE_MCP_TOKEN;\n if (token) headers[\"Authorization\"] = `Bearer ${token}`;\n const owner = env.AGENT_NATIVE_OWNER_EMAIL;\n if (owner) headers[\"X-Agent-Native-Owner-Email\"] = owner;\n return headers;\n}\n\nasync function probeOrigin(origin: string, timeoutMs = 800): Promise<boolean> {\n try {\n const res = await fetch(`${origin}${MCP_SUBPATH}`, {\n method: \"GET\",\n signal: AbortSignal.timeout(timeoutMs),\n });\n // Any HTTP response (even 401/405/406) means the server is up.\n return res.status > 0;\n } catch {\n return false;\n }\n}\n\n/**\n * Proxy mode: stdio Server ⇄ HTTP Client to the running app.\n *\n * We register the standard `tools/list` and `tools/call` handlers on the\n * stdio server and forward them verbatim to the upstream HTTP MCP server via\n * the SDK `Client`. The upstream owns tool definitions, results, and the\n * appended deep-link block / `_meta`, so nothing is duplicated here.\n */\nasync function runProxy(opts: RunMCPStdioOptions): Promise<void> {\n const { origin, appId } = await resolveLocalAppOrigin({\n cwd: opts.cwd,\n env: opts.env,\n appId: opts.appId,\n port: opts.port,\n });\n const env = opts.env ?? process.env;\n const target = `${origin}${MCP_SUBPATH}`;\n\n // Wait for the app to come up. The workspace gateway lazily boots an app's\n // dev server on first request, so a fresh `mcp serve` may briefly race the\n // boot. Hit the gateway path too so the lazy start is triggered.\n const deadline = Date.now() + (opts.waitForAppMs ?? 60_000);\n let up = await probeOrigin(origin);\n if (!up) {\n log(`Waiting for ${appId} at ${origin} …`);\n while (!up && Date.now() < deadline) {\n await new Promise((r) => setTimeout(r, 750));\n up = await probeOrigin(origin);\n }\n }\n if (!up) {\n throw new Error(\n `Timed out waiting for the local app at ${origin}. Start it with ` +\n `\\`agent-native dev\\` (or \\`agent-native workspace-dev\\`), or run ` +\n `\\`agent-native mcp serve --standalone\\` to build the server from disk.`,\n );\n }\n\n const { Client } = await import(\"@modelcontextprotocol/sdk/client/index.js\");\n const { StreamableHTTPClientTransport } =\n await import(\"@modelcontextprotocol/sdk/client/streamableHttp.js\");\n const { Server } = await import(\"@modelcontextprotocol/sdk/server/index.js\");\n const { StdioServerTransport } =\n await import(\"@modelcontextprotocol/sdk/server/stdio.js\");\n const { ListToolsRequestSchema, CallToolRequestSchema } =\n await import(\"@modelcontextprotocol/sdk/types.js\");\n\n // --- Upstream HTTP client -------------------------------------------------\n const clientTransport = new StreamableHTTPClientTransport(new URL(target), {\n requestInit: { headers: authHeaders(env) },\n });\n const client = new Client(\n { name: \"agent-native-mcp-proxy\", version: \"1.0.0\" },\n { capabilities: {} },\n );\n await client.connect(clientTransport);\n log(`Proxying stdio ⇄ ${target} (app: ${appId})`);\n\n // --- Downstream stdio server ---------------------------------------------\n const server = new Server(\n { name: `agent-native-${appId}`, version: \"1.0.0\" },\n { capabilities: { tools: {} } },\n );\n\n server.setRequestHandler(ListToolsRequestSchema, async (request: any) => {\n return client.listTools(request.params);\n });\n\n server.setRequestHandler(CallToolRequestSchema, async (request: any) => {\n // Forward the call verbatim; the upstream appends the deep-link block.\n return client.callTool(request.params);\n });\n\n const stdioTransport = new StdioServerTransport();\n await server.connect(stdioTransport);\n\n // Keep the proxy alive until the client/transport closes.\n await new Promise<void>((resolve) => {\n const done = () => resolve();\n stdioTransport.onclose = done;\n clientTransport.onclose = done;\n process.once(\"SIGINT\", done);\n process.once(\"SIGTERM\", done);\n });\n\n try {\n await client.close();\n } catch {\n // best-effort\n }\n}\n\n/**\n * Standalone mode: build the MCP server in-process from disk.\n *\n * No running server, no HMR — actions are discovered via\n * `autoDiscoverActions(cwd)` and the shared `createMCPServerForRequest`\n * builder is reused so behavior (tools, deep links, builtin cross-app tools)\n * matches the HTTP mount exactly.\n */\nasync function runStandalone(opts: RunMCPStdioOptions): Promise<void> {\n const cwd = opts.cwd ?? process.cwd();\n const env = opts.env ?? process.env;\n\n const { resolveLocalAppOrigin } = await import(\"./workspace-resolve.js\");\n let appId = opts.appId ?? \"app\";\n let origin: string | undefined;\n try {\n const resolved = await resolveLocalAppOrigin({\n cwd,\n env,\n appId: opts.appId,\n port: opts.port,\n });\n appId = resolved.appId;\n // Origin is best-effort here (server may not be running) — still useful\n // so a `link` builder's relative deep link becomes an absolute URL.\n origin = resolved.origin;\n } catch {\n // No workspace / can't resolve — fall back to a bare app id.\n }\n\n const { autoDiscoverActions } = await import(\"../server/action-discovery.js\");\n const { createMCPServerForRequest } = await import(\"./build-server.js\");\n const { StdioServerTransport } =\n await import(\"@modelcontextprotocol/sdk/server/stdio.js\");\n\n const actions = await autoDiscoverActions(cwd);\n log(\n `Standalone: discovered ${Object.keys(actions).length} action(s) in ${cwd}`,\n );\n\n const server = await createMCPServerForRequest(\n {\n name: appId.charAt(0).toUpperCase() + appId.slice(1),\n appId,\n description: `Agent-native ${appId} app (standalone MCP)`,\n actions,\n // No askAgent in standalone — there is no running engine/runtime here.\n // builtin cross-app tools stay on so `list_apps` / `open_app` /\n // `create_workspace_app` / `list_templates` still work from disk.\n },\n // No verified identity in standalone (no inbound auth header). Runs with\n // platform-default scope, same as a tokenless local HTTP mount.\n undefined,\n { origin },\n );\n\n const transport = new StdioServerTransport();\n await server.connect(transport);\n\n await new Promise<void>((resolve) => {\n const done = () => resolve();\n transport.onclose = done;\n process.once(\"SIGINT\", done);\n process.once(\"SIGTERM\", done);\n });\n}\n\n/**\n * Entry point for `agent-native mcp serve`. Defaults to proxy mode; pass\n * `standalone: true` to build the server from disk with no running app.\n */\nexport async function runMCPStdio(\n opts: RunMCPStdioOptions = {},\n): Promise<void> {\n if (opts.standalone) {\n await runStandalone(opts);\n return;\n }\n try {\n await runProxy(opts);\n } catch (err: any) {\n // Proxy couldn't reach a running app — surface a clear, actionable\n // message on stderr. We do NOT silently fall back to standalone: the\n // caller asked for the live registry; auto-falling-back would hide a\n // broken dev server and serve stale tools.\n log(`Proxy mode failed: ${err?.message ?? err}`);\n throw err;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"stdio.js","sourceRoot":"","sources":["../../src/mcp/stdio.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAEH,OAAO,EAAE,qBAAqB,EAAE,MAAM,wBAAwB,CAAC;AAkB/D,MAAM,WAAW,GAAG,oBAAoB,CAAC;AAEzC,SAAS,GAAG,CAAC,GAAW;IACtB,wEAAwE;IACxE,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,SAAS,GAAG,IAAI,CAAC,CAAC;AACzC,CAAC;AAED;;;;;;GAMG;AACH,SAAS,WAAW,CAAC,GAAsB;IACzC,MAAM,OAAO,GAA2B,EAAE,CAAC;IAC3C,MAAM,KAAK,GAAG,GAAG,CAAC,YAAY,IAAI,GAAG,CAAC,sBAAsB,CAAC;IAC7D,IAAI,KAAK;QAAE,OAAO,CAAC,eAAe,CAAC,GAAG,UAAU,KAAK,EAAE,CAAC;IACxD,MAAM,KAAK,GAAG,GAAG,CAAC,wBAAwB,CAAC;IAC3C,IAAI,KAAK;QAAE,OAAO,CAAC,4BAA4B,CAAC,GAAG,KAAK,CAAC;IACzD,OAAO,OAAO,CAAC;AACjB,CAAC;AAED,KAAK,UAAU,WAAW,CAAC,MAAc,EAAE,SAAS,GAAG,GAAG;IACxD,IAAI,CAAC;QACH,MAAM,GAAG,GAAG,MAAM,KAAK,CAAC,GAAG,MAAM,GAAG,WAAW,EAAE,EAAE;YACjD,MAAM,EAAE,KAAK;YACb,MAAM,EAAE,WAAW,CAAC,OAAO,CAAC,SAAS,CAAC;SACvC,CAAC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AAI,CAAC,CAAC;QAC1B,OAAO;IACT,CAAC;IACD,IAAI,CAAC;QACH,MAAM,QAAQ,CAAC,IAAI,CAAC,CAAC;IACvB,CAAC;IAAC,OAAO,GAAQ,EAAE,CAAC;QAClB,mEAAmE;QACnE,qEAAqE;QACrE,qEAAqE;QACrE,2CAA2C;QAC3C,GAAG,CAAC,sBAAsB,GAAG,EAAE,OAAO,IAAI,GAAG,EAAE,CAAC,CAAC;QACjD,MAAM,GAAG,CAAC;IACZ,CAAC;AACH,CAAC","sourcesContent":["/**\n * MCP **stdio** transport for the `agent-native mcp serve` command.\n *\n * This is the binary external coding agents (Claude Code, Claude Cowork,\n * Codex) actually launch — they speak MCP over a child process's stdio, not\n * HTTP. We expose the agent-native app's MCP surface over stdio in two modes:\n *\n * - **proxy (default)** — connect an MCP `Client` over\n * `StreamableHTTPClientTransport` to the *already-running* local app's\n * `http://127.0.0.1:<port>/_agent-native/mcp`, and run a stdio `Server`\n * that forwards tools and optional MCP App resources to it. The live app\n * is the single source of truth: HMR'd actions, the real registry, correct\n * per-request deep links, and tenant scoping all come for free. If the\n * app isn't running, we wait briefly for it (the workspace gateway boots\n * it lazily on first request).\n *\n * - **standalone (`--standalone`)** — no running server, no HMR. Build the\n * MCP server in-process from `autoDiscoverActions(cwd)` +\n * `createMCPServerForRequest`, connected straight to a\n * `StdioServerTransport`. Useful in CI / when nothing is serving.\n *\n * Node-only: imports `node:*` and the SDK stdio/http transports. Never part\n * of the serverless bundle.\n */\n\nimport { resolveLocalAppOrigin } from \"./workspace-resolve.js\";\nimport type { ServerCapabilities } from \"@modelcontextprotocol/sdk/types.js\";\n\nexport interface RunMCPStdioOptions {\n /** App id to bridge to (workspace). Optional in a single-app project. */\n appId?: string;\n /** Explicit port of the running app's dev server. Overrides discovery. */\n port?: number;\n /** Skip the HTTP proxy and build the server in-process from disk. */\n standalone?: boolean;\n /** Working directory (defaults to process.cwd()). */\n cwd?: string;\n /** Env (defaults to process.env). */\n env?: NodeJS.ProcessEnv;\n /** Max ms to wait for the running app before failing (proxy mode). */\n waitForAppMs?: number;\n}\n\nconst MCP_SUBPATH = \"/_agent-native/mcp\";\n\nfunction log(msg: string): void {\n // stderr only — stdout is the MCP protocol channel and must stay clean.\n process.stderr.write(`[mcp] ${msg}\\n`);\n}\n\n/**\n * Owner identity the installer wrote into the client config's env. Passed\n * through to the HTTP MCP endpoint as a JWT/identity bearer (when present)\n * so tool runs stay tenant-scoped. For local dev with a static ACCESS_TOKEN\n * the email is informational; for hosted JWT auth the token already carries\n * `sub`, so we only add an `X-Agent-Native-Owner-Email` hint header.\n */\nfunction authHeaders(env: NodeJS.ProcessEnv): Record<string, string> {\n const headers: Record<string, string> = {};\n const token = env.ACCESS_TOKEN || env.AGENT_NATIVE_MCP_TOKEN;\n if (token) headers[\"Authorization\"] = `Bearer ${token}`;\n const owner = env.AGENT_NATIVE_OWNER_EMAIL;\n if (owner) headers[\"X-Agent-Native-Owner-Email\"] = owner;\n return headers;\n}\n\nasync function probeOrigin(origin: string, timeoutMs = 800): Promise<boolean> {\n try {\n const res = await fetch(`${origin}${MCP_SUBPATH}`, {\n method: \"GET\",\n signal: AbortSignal.timeout(timeoutMs),\n });\n // Any HTTP response (even 401/405/406) means the server is up.\n return res.status > 0;\n } catch {\n return false;\n }\n}\n\n/**\n * Proxy mode: stdio Server ⇄ HTTP Client to the running app.\n *\n * We register the standard handlers on the stdio server and forward them\n * verbatim to the upstream HTTP MCP server via the SDK `Client`. The upstream\n * owns tool definitions, results, MCP App resources, and the appended\n * deep-link block / `_meta`, so nothing is duplicated here.\n */\nasync function runProxy(opts: RunMCPStdioOptions): Promise<void> {\n const { origin, appId } = await resolveLocalAppOrigin({\n cwd: opts.cwd,\n env: opts.env,\n appId: opts.appId,\n port: opts.port,\n });\n const env = opts.env ?? process.env;\n const target = `${origin}${MCP_SUBPATH}`;\n\n // Wait for the app to come up. The workspace gateway lazily boots an app's\n // dev server on first request, so a fresh `mcp serve` may briefly race the\n // boot. Hit the gateway path too so the lazy start is triggered.\n const deadline = Date.now() + (opts.waitForAppMs ?? 60_000);\n let up = await probeOrigin(origin);\n if (!up) {\n log(`Waiting for ${appId} at ${origin} …`);\n while (!up && Date.now() < deadline) {\n await new Promise((r) => setTimeout(r, 750));\n up = await probeOrigin(origin);\n }\n }\n if (!up) {\n throw new Error(\n `Timed out waiting for the local app at ${origin}. Start it with ` +\n `\\`agent-native dev\\` (or \\`agent-native workspace-dev\\`), or run ` +\n `\\`agent-native mcp serve --standalone\\` to build the server from disk.`,\n );\n }\n\n const { Client } = await import(\"@modelcontextprotocol/sdk/client/index.js\");\n const { StreamableHTTPClientTransport } =\n await import(\"@modelcontextprotocol/sdk/client/streamableHttp.js\");\n const { Server } = await import(\"@modelcontextprotocol/sdk/server/index.js\");\n const { StdioServerTransport } =\n await import(\"@modelcontextprotocol/sdk/server/stdio.js\");\n const {\n ListToolsRequestSchema,\n CallToolRequestSchema,\n ListResourcesRequestSchema,\n ReadResourceRequestSchema,\n ListResourceTemplatesRequestSchema,\n } = await import(\"@modelcontextprotocol/sdk/types.js\");\n\n // --- Upstream HTTP client -------------------------------------------------\n const clientTransport = new StreamableHTTPClientTransport(new URL(target), {\n requestInit: { headers: authHeaders(env) },\n });\n const client = new Client(\n { name: \"agent-native-mcp-proxy\", version: \"1.0.0\" },\n { capabilities: {} },\n );\n await client.connect(clientTransport);\n log(`Proxying stdio ⇄ ${target} (app: ${appId})`);\n\n // --- Downstream stdio server ---------------------------------------------\n const upstreamCapabilities = client.getServerCapabilities();\n const capabilities: ServerCapabilities = { tools: {} };\n if (upstreamCapabilities?.resources) capabilities.resources = {};\n if (upstreamCapabilities?.extensions) {\n capabilities.extensions = upstreamCapabilities.extensions;\n }\n\n const server = new Server(\n { name: `agent-native-${appId}`, version: \"1.0.0\" },\n { capabilities },\n );\n\n server.setRequestHandler(ListToolsRequestSchema, async (request: any) => {\n return client.listTools(request.params);\n });\n\n server.setRequestHandler(CallToolRequestSchema, async (request: any) => {\n // Forward the call verbatim; the upstream appends the deep-link block.\n return client.callTool(request.params);\n });\n\n if (upstreamCapabilities?.resources) {\n server.setRequestHandler(\n ListResourcesRequestSchema,\n async (request: any) => {\n return client.listResources(request.params);\n },\n );\n\n server.setRequestHandler(\n ListResourceTemplatesRequestSchema,\n async (request: any) => {\n return client.listResourceTemplates(request.params);\n },\n );\n\n server.setRequestHandler(\n ReadResourceRequestSchema,\n async (request: any) => {\n return client.readResource(request.params);\n },\n );\n }\n\n const stdioTransport = new StdioServerTransport();\n await server.connect(stdioTransport);\n\n // Keep the proxy alive until the client/transport closes.\n await new Promise<void>((resolve) => {\n const done = () => resolve();\n stdioTransport.onclose = done;\n clientTransport.onclose = done;\n process.once(\"SIGINT\", done);\n process.once(\"SIGTERM\", done);\n });\n\n try {\n await client.close();\n } catch {\n // best-effort\n }\n}\n\n/**\n * Standalone mode: build the MCP server in-process from disk.\n *\n * No running server, no HMR — actions are discovered via\n * `autoDiscoverActions(cwd)` and the shared `createMCPServerForRequest`\n * builder is reused so behavior (tools, deep links, builtin cross-app tools)\n * matches the HTTP mount exactly.\n */\nasync function runStandalone(opts: RunMCPStdioOptions): Promise<void> {\n const cwd = opts.cwd ?? process.cwd();\n const env = opts.env ?? process.env;\n\n const { resolveLocalAppOrigin } = await import(\"./workspace-resolve.js\");\n let appId = opts.appId ?? \"app\";\n let origin: string | undefined;\n try {\n const resolved = await resolveLocalAppOrigin({\n cwd,\n env,\n appId: opts.appId,\n port: opts.port,\n });\n appId = resolved.appId;\n // Origin is best-effort here (server may not be running) — still useful\n // so a `link` builder's relative deep link becomes an absolute URL.\n origin = resolved.origin;\n } catch {\n // No workspace / can't resolve — fall back to a bare app id.\n }\n\n const { autoDiscoverActions } = await import(\"../server/action-discovery.js\");\n const { createMCPServerForRequest } = await import(\"./build-server.js\");\n const { StdioServerTransport } =\n await import(\"@modelcontextprotocol/sdk/server/stdio.js\");\n\n const actions = await autoDiscoverActions(cwd);\n log(\n `Standalone: discovered ${Object.keys(actions).length} action(s) in ${cwd}`,\n );\n\n const server = await createMCPServerForRequest(\n {\n name: appId.charAt(0).toUpperCase() + appId.slice(1),\n appId,\n description: `Agent-native ${appId} app (standalone MCP)`,\n actions,\n // No askAgent in standalone — there is no running engine/runtime here.\n // builtin cross-app tools stay on so `list_apps` / `open_app` /\n // `create_workspace_app` / `list_templates` still work from disk.\n },\n // No verified identity in standalone (no inbound auth header). Runs with\n // platform-default scope, same as a tokenless local HTTP mount.\n undefined,\n { origin },\n );\n\n const transport = new StdioServerTransport();\n await server.connect(transport);\n\n await new Promise<void>((resolve) => {\n const done = () => resolve();\n transport.onclose = done;\n process.once(\"SIGINT\", done);\n process.once(\"SIGTERM\", done);\n });\n}\n\n/**\n * Entry point for `agent-native mcp serve`. Defaults to proxy mode; pass\n * `standalone: true` to build the server from disk with no running app.\n */\nexport async function runMCPStdio(\n opts: RunMCPStdioOptions = {},\n): Promise<void> {\n if (opts.standalone) {\n await runStandalone(opts);\n return;\n }\n try {\n await runProxy(opts);\n } catch (err: any) {\n // Proxy couldn't reach a running app — surface a clear, actionable\n // message on stderr. We do NOT silently fall back to standalone: the\n // caller asked for the live registry; auto-falling-back would hide a\n // broken dev server and serve stale tools.\n log(`Proxy mode failed: ${err?.message ?? err}`);\n throw err;\n }\n}\n"]}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import type { McpTool } from "./manager.js";
|
|
2
|
+
export declare const MCP_ACTION_RESULT_MARKER: "__agentNativeMcpToolResult";
|
|
3
|
+
export interface AgentMcpAppResourceContent {
|
|
4
|
+
uri: string;
|
|
5
|
+
mimeType?: string;
|
|
6
|
+
text?: string;
|
|
7
|
+
blob?: string;
|
|
8
|
+
_meta?: Record<string, unknown>;
|
|
9
|
+
}
|
|
10
|
+
export interface AgentMcpAppPayload {
|
|
11
|
+
serverId: string;
|
|
12
|
+
toolName: string;
|
|
13
|
+
originalToolName: string;
|
|
14
|
+
resourceUri: string;
|
|
15
|
+
toolInput: Record<string, unknown>;
|
|
16
|
+
toolResult: Record<string, unknown>;
|
|
17
|
+
tool?: {
|
|
18
|
+
name: string;
|
|
19
|
+
title?: string;
|
|
20
|
+
description?: string;
|
|
21
|
+
inputSchema?: Record<string, unknown>;
|
|
22
|
+
outputSchema?: Record<string, unknown>;
|
|
23
|
+
annotations?: Record<string, unknown>;
|
|
24
|
+
_meta?: Record<string, unknown>;
|
|
25
|
+
};
|
|
26
|
+
resource?: AgentMcpAppResourceContent;
|
|
27
|
+
}
|
|
28
|
+
export interface McpActionResult {
|
|
29
|
+
[MCP_ACTION_RESULT_MARKER]: true;
|
|
30
|
+
text: string;
|
|
31
|
+
raw: unknown;
|
|
32
|
+
serverId: string;
|
|
33
|
+
toolName: string;
|
|
34
|
+
originalToolName: string;
|
|
35
|
+
input: Record<string, unknown>;
|
|
36
|
+
mcpApp?: AgentMcpAppPayload;
|
|
37
|
+
}
|
|
38
|
+
export declare function isMcpActionResult(value: unknown): value is McpActionResult;
|
|
39
|
+
export declare function toolForMcpAppPayload(tool: McpTool): AgentMcpAppPayload["tool"];
|
|
40
|
+
//# sourceMappingURL=app-result.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"app-result.d.ts","sourceRoot":"","sources":["../../src/mcp-client/app-result.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAE5C,eAAO,MAAM,wBAAwB,EAAG,4BAAqC,CAAC;AAE9E,MAAM,WAAW,0BAA0B;IACzC,GAAG,EAAE,MAAM,CAAC;IACZ,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACjC;AAED,MAAM,WAAW,kBAAkB;IACjC,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,MAAM,CAAC;IACjB,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3
|
+
return (!!value &&
|
|
4
|
+
typeof value === "object" &&
|
|
5
|
+
value[MCP_ACTION_RESULT_MARKER] === true &&
|
|
6
|
+
typeof value.text === "string");
|
|
7
|
+
}
|
|
8
|
+
export function toolForMcpAppPayload(tool) {
|
|
9
|
+
return {
|
|
10
|
+
name: tool.originalName,
|
|
11
|
+
...(tool.title ? { title: tool.title } : {}),
|
|
12
|
+
description: tool.description,
|
|
13
|
+
inputSchema: tool.inputSchema,
|
|
14
|
+
...(tool.outputSchema ? { outputSchema: tool.outputSchema } : {}),
|
|
15
|
+
...(tool.annotations ? { annotations: tool.annotations } : {}),
|
|
16
|
+
...(tool._meta ? { _meta: tool._meta } : {}),
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
//# sourceMappingURL=app-result.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"app-result.js","sourceRoot":"","sources":["../../src/mcp-client/app-result.ts"],"names":[],"mappings":"AAEA,MAAM,CAAC,MAAM,wBAAwB,GAAG,4BAAqC,CAAC;AAwC9E,MAAM,UAAU,iBAAiB,CAAC,KAAc;IAC9C,OAAO,CACL,CAAC,CAAC,KAAK;QACP,OAAO,KAAK,KAAK,QAAQ;QACxB,KAAiC,CAAC,wBAAwB,CAAC,KAAK,IAAI;QACrE,OAAQ,KAAiC,CAAC,IAAI,KAAK,QAAQ,CAC5D,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,oBAAoB,CAClC,IAAa;IAEb,OAAO;QACL,IAAI,EAAE,IAAI,CAAC,YAAY;QACvB,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAC5C,WAAW,EAAE,IAAI,CAAC,WAAW;QAC7B,WAAW,EAAE,IAAI,CAAC,WAAW;QAC7B,GAAG,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC,CAAC,EAAE,YAAY,EAAE,IAAI,CAAC,YAAY,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QACjE,GAAG,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE,WAAW,EAAE,IAAI,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAC9D,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KAC7C,CAAC;AACJ,CAAC","sourcesContent":["import type { McpTool } from \"./manager.js\";\n\nexport const MCP_ACTION_RESULT_MARKER = \"__agentNativeMcpToolResult\" as const;\n\nexport interface AgentMcpAppResourceContent {\n uri: string;\n mimeType?: string;\n text?: string;\n blob?: string;\n _meta?: Record<string, unknown>;\n}\n\nexport interface AgentMcpAppPayload {\n serverId: string;\n toolName: string;\n originalToolName: string;\n resourceUri: string;\n toolInput: Record<string, unknown>;\n toolResult: Record<string, unknown>;\n tool?: {\n name: string;\n title?: string;\n description?: string;\n inputSchema?: Record<string, unknown>;\n outputSchema?: Record<string, unknown>;\n annotations?: Record<string, unknown>;\n _meta?: Record<string, unknown>;\n };\n resource?: AgentMcpAppResourceContent;\n}\n\nexport interface McpActionResult {\n [MCP_ACTION_RESULT_MARKER]: true;\n text: string;\n raw: unknown;\n serverId: string;\n toolName: string;\n originalToolName: string;\n input: Record<string, unknown>;\n mcpApp?: AgentMcpAppPayload;\n}\n\nexport function isMcpActionResult(value: unknown): value is McpActionResult {\n return (\n !!value &&\n typeof value === \"object\" &&\n (value as Record<string, unknown>)[MCP_ACTION_RESULT_MARKER] === true &&\n typeof (value as Record<string, unknown>).text === \"string\"\n );\n}\n\nexport function toolForMcpAppPayload(\n tool: McpTool,\n): AgentMcpAppPayload[\"tool\"] {\n return {\n name: tool.originalName,\n ...(tool.title ? { title: tool.title } : {}),\n description: tool.description,\n inputSchema: tool.inputSchema,\n ...(tool.outputSchema ? { outputSchema: tool.outputSchema } : {}),\n ...(tool.annotations ? { annotations: tool.annotations } : {}),\n ...(tool._meta ? { _meta: tool._meta } : {}),\n };\n}\n"]}
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* to the agent-chat tool-use loop.
|
|
6
6
|
*/
|
|
7
7
|
export { loadMcpConfig, autoDetectMcpConfig, type McpConfig, type McpServerConfig, } from "./config.js";
|
|
8
|
-
export { McpClientManager, parseMcpToolName, MCP_TOOL_PREFIX, type McpTool, type McpClientManagerOptions, } from "./manager.js";
|
|
8
|
+
export { McpClientManager, buildMcpToolName, parseMcpToolName, MCP_TOOL_PREFIX, type McpTool, type McpClientManagerOptions, } from "./manager.js";
|
|
9
9
|
export { listRemoteServers, addRemoteServer, removeRemoteServer, validateRemoteUrl, normalizeServerName, mergedConfigKey, parseMergedKey, hashEmail, toHttpServerConfig, toHttpServerConfigAsync, materializeHeaders, type RemoteMcpScope, type StoredRemoteMcpServer, } from "./remote-store.js";
|
|
10
10
|
export { BUILTIN_MCP_CAPABILITIES, getBuiltinMcpCapability, isBuiltinMcpCapabilityAvailable, normalizeBuiltinMcpCapabilityIds, toBuiltinMcpServerConfig, type BuiltinMcpCapability, type BuiltinMcpCapabilityId, } from "./builtin-capabilities.js";
|
|
11
11
|
export { builtinMcpCapabilitiesSettingsKey, listEnabledBuiltinMcpCapabilities, setEnabledBuiltinMcpCapabilities, setBuiltinMcpCapabilityEnabled, type StoredBuiltinMcpCapabilities, } from "./builtin-store.js";
|
|
@@ -13,13 +13,14 @@ export { mountMcpServersRoutes, buildMergedConfig, builtinMergedConfigKey, type
|
|
|
13
13
|
export { mountMcpHubRoutes, listHubServers, getHubStatus, isHubServeEnabled, isHubConsumeEnabled, type HubServerRecord, type HubServersResponse, } from "./hub-routes.js";
|
|
14
14
|
export { fetchHubServers } from "./hub-client.js";
|
|
15
15
|
export { isMcpToolAllowedForRequest } from "./visibility.js";
|
|
16
|
+
export { MCP_ACTION_RESULT_MARKER, isMcpActionResult, type AgentMcpAppPayload, type AgentMcpAppResourceContent, type McpActionResult, } from "./app-result.js";
|
|
16
17
|
/**
|
|
17
18
|
* Convert MCP tools into `ActionEntry` values suitable for registration in
|
|
18
19
|
* the agent's action registry. Each tool is marked `http: false` so it's
|
|
19
20
|
* never auto-mounted as an HTTP endpoint — MCP tools are agent-only.
|
|
20
21
|
*/
|
|
21
22
|
import type { ActionEntry } from "../agent/production-agent.js";
|
|
22
|
-
import type { McpClientManager } from "./manager.js";
|
|
23
|
+
import type { McpClientManager, McpTool } from "./manager.js";
|
|
23
24
|
export declare function mcpToolsToActionEntries(manager: McpClientManager): Record<string, ActionEntry>;
|
|
24
25
|
/**
|
|
25
26
|
* Mutate a target action dict in place so it matches the current MCP tool set:
|
|
@@ -31,4 +32,6 @@ export declare function mcpToolsToActionEntries(manager: McpClientManager): Reco
|
|
|
31
32
|
* registries in sync after `McpClientManager.reconfigure()` runs.
|
|
32
33
|
*/
|
|
33
34
|
export declare function syncMcpActionEntries(manager: McpClientManager, target: Record<string, ActionEntry>): void;
|
|
35
|
+
export declare function isVisibleToMcpApp(tool: McpTool): boolean;
|
|
36
|
+
export declare function flattenMcpToolResult(result: unknown): string;
|
|
34
37
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/mcp-client/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EACL,aAAa,EACb,mBAAmB,EACnB,KAAK,SAAS,EACd,KAAK,eAAe,GACrB,MAAM,aAAa,CAAC;AAErB,OAAO,EACL,gBAAgB,EAChB,gBAAgB,EAChB,eAAe,EACf,KAAK,OAAO,EACZ,KAAK,uBAAuB,GAC7B,MAAM,cAAc,CAAC;AAEtB,OAAO,EACL,iBAAiB,EACjB,eAAe,EACf,kBAAkB,EAClB,iBAAiB,EACjB,mBAAmB,EACnB,eAAe,EACf,cAAc,EACd,SAAS,EACT,kBAAkB,EAClB,uBAAuB,EACvB,kBAAkB,EAClB,KAAK,cAAc,EACnB,KAAK,qBAAqB,GAC3B,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EACL,wBAAwB,EACxB,uBAAuB,EACvB,+BAA+B,EAC/B,gCAAgC,EAChC,wBAAwB,EACxB,KAAK,oBAAoB,EACzB,KAAK,sBAAsB,GAC5B,MAAM,2BAA2B,CAAC;AAEnC,OAAO,EACL,iCAAiC,EACjC,iCAAiC,EACjC,gCAAgC,EAChC,8BAA8B,EAC9B,KAAK,4BAA4B,GAClC,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EACL,qBAAqB,EACrB,iBAAiB,EACjB,sBAAsB,EACtB,KAAK,uBAAuB,GAC7B,MAAM,aAAa,CAAC;AAErB,OAAO,EACL,iBAAiB,EACjB,cAAc,EACd,YAAY,EACZ,iBAAiB,EACjB,mBAAmB,EACnB,KAAK,eAAe,EACpB,KAAK,kBAAkB,GACxB,MAAM,iBAAiB,CAAC;AAEzB,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAElD,OAAO,EAAE,0BAA0B,EAAE,MAAM,iBAAiB,CAAC;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/mcp-client/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EACL,aAAa,EACb,mBAAmB,EACnB,KAAK,SAAS,EACd,KAAK,eAAe,GACrB,MAAM,aAAa,CAAC;AAErB,OAAO,EACL,gBAAgB,EAChB,gBAAgB,EAChB,gBAAgB,EAChB,eAAe,EACf,KAAK,OAAO,EACZ,KAAK,uBAAuB,GAC7B,MAAM,cAAc,CAAC;AAEtB,OAAO,EACL,iBAAiB,EACjB,eAAe,EACf,kBAAkB,EAClB,iBAAiB,EACjB,mBAAmB,EACnB,eAAe,EACf,cAAc,EACd,SAAS,EACT,kBAAkB,EAClB,uBAAuB,EACvB,kBAAkB,EAClB,KAAK,cAAc,EACnB,KAAK,qBAAqB,GAC3B,MAAM,m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