xmcp 0.6.7 → 0.6.9
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/cli.js +36 -15
- package/dist/compiler/config/index.d.ts +7 -0
- package/dist/compiler/config/schemas/template.d.ts +5 -0
- package/dist/host-bridge.d.ts +4 -0
- package/dist/host-bridge.js +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +5 -5
- package/dist/runtime/adapter-express.js +21 -19
- package/dist/runtime/adapter-nestjs.js +21 -19
- package/dist/runtime/adapter-nextjs.js +21 -19
- package/dist/runtime/contexts/client-info-context.d.ts +8 -0
- package/dist/runtime/http.js +26 -24
- package/dist/runtime/stdio.js +32 -30
- package/dist/runtime/utils/mcp-app-protocol.d.ts +14 -0
- package/dist/runtime/utils/mcp-app-types.d.ts +103 -0
- package/dist/runtime/utils/mcp-host-bridge.d.ts +43 -0
- package/dist/runtime/utils/server.d.ts +3 -1
- package/dist/types/ui-meta.d.ts +15 -0
- package/package.json +12 -1
- package/src/compiler/client/component-compiler.ts +26 -5
- package/src/compiler/config/injection.ts +1 -0
- package/src/compiler/config/schemas/template.ts +13 -0
- package/src/compiler/get-bundler-config/index.ts +1 -0
- package/src/host-bridge.ts +36 -0
- package/src/index.ts +36 -0
- package/src/runtime/adapters/nextjs/handler/server-lifecycle.ts +2 -1
- package/src/runtime/contexts/client-info-context.ts +16 -0
- package/src/runtime/transports/http/stateless-streamable-http.ts +11 -89
- package/src/runtime/transports/stdio/index.ts +40 -7
- package/src/runtime/utils/__tests__/client-info.test.ts +19 -0
- package/src/runtime/utils/__tests__/tool-extra.test.ts +39 -0
- package/src/runtime/utils/client-info.ts +7 -0
- package/src/runtime/utils/mcp-app-protocol.ts +16 -0
- package/src/runtime/utils/mcp-app-types.ts +113 -0
- package/src/runtime/utils/mcp-host-bridge.ts +473 -0
- package/src/runtime/utils/react/generate-html.ts +12 -4
- package/src/runtime/utils/server.ts +3 -2
- package/src/runtime/utils/transformers/tool.ts +10 -1
- package/src/runtime/utils/ui/__tests__/split-meta.test.ts +42 -0
- package/src/runtime/utils/ui/split-meta.ts +4 -1
- package/src/types/ui-meta.ts +17 -1
|
@@ -3,6 +3,7 @@ import assert from "node:assert";
|
|
|
3
3
|
import {
|
|
4
4
|
extractClientInfoFromMessage,
|
|
5
5
|
extractClientInfoFromMessages,
|
|
6
|
+
mapImplementationToClientInfo,
|
|
6
7
|
} from "../client-info";
|
|
7
8
|
|
|
8
9
|
test("extractClientInfoFromMessage returns undefined for non-initialize methods", () => {
|
|
@@ -78,3 +79,21 @@ test("extractClientInfoFromMessages supports batch requests", () => {
|
|
|
78
79
|
version: "1.2.3",
|
|
79
80
|
});
|
|
80
81
|
});
|
|
82
|
+
|
|
83
|
+
test("mapImplementationToClientInfo maps SDK implementation shape", () => {
|
|
84
|
+
const result = mapImplementationToClientInfo({
|
|
85
|
+
name: "claude-code",
|
|
86
|
+
version: "2.1.0",
|
|
87
|
+
title: "Claude Code",
|
|
88
|
+
websiteUrl: "https://claude.ai",
|
|
89
|
+
description: "CLI coding agent",
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
assert.deepStrictEqual(result, {
|
|
93
|
+
name: "claude-code",
|
|
94
|
+
version: "2.1.0",
|
|
95
|
+
title: "Claude Code",
|
|
96
|
+
websiteUrl: "https://claude.ai",
|
|
97
|
+
description: "CLI coding agent",
|
|
98
|
+
});
|
|
99
|
+
});
|
|
@@ -5,6 +5,7 @@ import {
|
|
|
5
5
|
type UserToolResponse,
|
|
6
6
|
} from "../transformers/tool";
|
|
7
7
|
import { httpRequestContextProvider } from "../../contexts/http-request-context";
|
|
8
|
+
import { clientInfoContextProvider } from "../../contexts/client-info-context";
|
|
8
9
|
|
|
9
10
|
type MinimalExtra = {
|
|
10
11
|
signal: AbortSignal;
|
|
@@ -108,3 +109,41 @@ test("transformToolHandler leaves clientInfo undefined when request has no initi
|
|
|
108
109
|
],
|
|
109
110
|
});
|
|
110
111
|
});
|
|
112
|
+
|
|
113
|
+
test("transformToolHandler uses stdio clientInfo context as fallback", async () => {
|
|
114
|
+
const transformedHandler = transformToolHandler((_args, extra) => {
|
|
115
|
+
return {
|
|
116
|
+
structuredContent: {
|
|
117
|
+
clientInfoName: extra.clientInfo?.name,
|
|
118
|
+
clientInfoVersion: extra.clientInfo?.version,
|
|
119
|
+
},
|
|
120
|
+
};
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
const result = await new Promise<UserToolResponse>((resolve, reject) => {
|
|
124
|
+
clientInfoContextProvider(
|
|
125
|
+
{
|
|
126
|
+
clientInfo: {
|
|
127
|
+
name: "opencode",
|
|
128
|
+
version: "1.2.3",
|
|
129
|
+
},
|
|
130
|
+
},
|
|
131
|
+
() => {
|
|
132
|
+
invokeHandler(transformedHandler, "rpc-3").then(resolve).catch(reject);
|
|
133
|
+
}
|
|
134
|
+
);
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
assert.deepStrictEqual(result, {
|
|
138
|
+
structuredContent: {
|
|
139
|
+
clientInfoName: "opencode",
|
|
140
|
+
clientInfoVersion: "1.2.3",
|
|
141
|
+
},
|
|
142
|
+
content: [
|
|
143
|
+
{
|
|
144
|
+
type: "text",
|
|
145
|
+
text: '{"clientInfoName":"opencode","clientInfoVersion":"1.2.3"}',
|
|
146
|
+
},
|
|
147
|
+
],
|
|
148
|
+
});
|
|
149
|
+
});
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { JsonRpcMessage } from "@/runtime/transports/http/base-streamable-http";
|
|
2
2
|
import type { McpClientInfo } from "@/types/client-info";
|
|
3
|
+
import type { Implementation } from "@modelcontextprotocol/sdk/types";
|
|
3
4
|
|
|
4
5
|
const isObject = (value: unknown): value is Record<string, unknown> => {
|
|
5
6
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
@@ -39,6 +40,12 @@ const parseClientInfoCandidate = (
|
|
|
39
40
|
return result;
|
|
40
41
|
};
|
|
41
42
|
|
|
43
|
+
export const mapImplementationToClientInfo = (
|
|
44
|
+
implementation: Implementation | undefined
|
|
45
|
+
): McpClientInfo | undefined => {
|
|
46
|
+
return parseClientInfoCandidate(implementation);
|
|
47
|
+
};
|
|
48
|
+
|
|
42
49
|
export const extractClientInfoFromMessage = (
|
|
43
50
|
message: JsonRpcMessage | undefined
|
|
44
51
|
): McpClientInfo | undefined => {
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export const MCP_APPS_PROTOCOL_VERSION = "2026-01-26";
|
|
2
|
+
|
|
3
|
+
export const INITIALIZE_METHOD = "ui/initialize";
|
|
4
|
+
export const INITIALIZED_METHOD = "ui/notifications/initialized";
|
|
5
|
+
export const REQUEST_DISPLAY_MODE_METHOD = "ui/request-display-mode";
|
|
6
|
+
export const REQUEST_DISPLAY_MODE_METHOD_LEGACY = "ui/requestDisplayMode";
|
|
7
|
+
export const OPEN_LINK_METHOD = "ui/open-link";
|
|
8
|
+
export const OPEN_LINK_METHOD_LEGACY = "ui/openLink";
|
|
9
|
+
export const UPDATE_MODEL_CONTEXT_METHOD = "ui/update-model-context";
|
|
10
|
+
export const UI_MESSAGE_METHOD = "ui/message";
|
|
11
|
+
export const LOG_MESSAGE_METHOD = "notifications/message";
|
|
12
|
+
export const RESOURCES_READ_METHOD = "resources/read";
|
|
13
|
+
export const HOST_CONTEXT_CHANGED_METHOD =
|
|
14
|
+
"ui/notifications/host-context-changed";
|
|
15
|
+
export const HOST_CONTEXT_CHANGED_METHOD_LEGACY = "ui/hostContextChanged";
|
|
16
|
+
export const SIZE_CHANGED_METHOD = "ui/notifications/size-changed";
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
export type McpUiDisplayMode = "inline" | "fullscreen" | "pip";
|
|
2
|
+
|
|
3
|
+
export interface McpHostCallToolParams {
|
|
4
|
+
name: string;
|
|
5
|
+
arguments?: Record<string, unknown>;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export interface McpHostOpenLinkParams {
|
|
9
|
+
url: string;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface McpHostRequestDisplayModeParams {
|
|
13
|
+
mode: McpUiDisplayMode;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface McpHostRequestDisplayModeResult {
|
|
17
|
+
mode: McpUiDisplayMode | string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface McpHostSendMessageParams {
|
|
21
|
+
role?: string;
|
|
22
|
+
content: unknown;
|
|
23
|
+
[key: string]: unknown;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface McpHostUpdateModelContextParams {
|
|
27
|
+
content?: unknown;
|
|
28
|
+
role?: string;
|
|
29
|
+
[key: string]: unknown;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface McpHostToolContentItem {
|
|
33
|
+
type: string;
|
|
34
|
+
text?: string;
|
|
35
|
+
[key: string]: unknown;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface McpHostToolResult {
|
|
39
|
+
content?: McpHostToolContentItem[];
|
|
40
|
+
structuredContent?: unknown;
|
|
41
|
+
isError?: boolean;
|
|
42
|
+
[key: string]: unknown;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface McpHostResourceContentItem {
|
|
46
|
+
uri?: string;
|
|
47
|
+
mimeType?: string;
|
|
48
|
+
text?: string;
|
|
49
|
+
blob?: string;
|
|
50
|
+
[key: string]: unknown;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export interface McpHostReadResourceResult {
|
|
54
|
+
contents?: McpHostResourceContentItem[];
|
|
55
|
+
[key: string]: unknown;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export interface McpHostMessageResult {
|
|
59
|
+
role?: string;
|
|
60
|
+
content?: unknown;
|
|
61
|
+
[key: string]: unknown;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export interface McpHostModelContextResult {
|
|
65
|
+
ok?: boolean;
|
|
66
|
+
[key: string]: unknown;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export interface McpHostContainerDimensions {
|
|
70
|
+
width?: number;
|
|
71
|
+
height?: number;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export interface McpHostStyleContext {
|
|
75
|
+
variables?: Record<string, string>;
|
|
76
|
+
css?: {
|
|
77
|
+
fonts?: string[];
|
|
78
|
+
[key: string]: unknown;
|
|
79
|
+
};
|
|
80
|
+
[key: string]: unknown;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export interface McpHostContext {
|
|
84
|
+
theme?: string;
|
|
85
|
+
displayMode?: McpUiDisplayMode | string;
|
|
86
|
+
locale?: string;
|
|
87
|
+
timeZone?: string;
|
|
88
|
+
platform?: string;
|
|
89
|
+
availableDisplayModes?: McpUiDisplayMode[];
|
|
90
|
+
containerDimensions?: McpHostContainerDimensions;
|
|
91
|
+
safeAreaInsets?: {
|
|
92
|
+
top?: number;
|
|
93
|
+
right?: number;
|
|
94
|
+
bottom?: number;
|
|
95
|
+
left?: number;
|
|
96
|
+
};
|
|
97
|
+
toolInfo?: Record<string, unknown>;
|
|
98
|
+
deviceCapabilities?: Record<string, unknown>;
|
|
99
|
+
styles?: McpHostStyleContext;
|
|
100
|
+
[key: string]: unknown;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export interface McpHostCapabilities {
|
|
104
|
+
serverTools?: { listChanged?: boolean; call?: boolean };
|
|
105
|
+
serverResources?: { listChanged?: boolean; read?: boolean };
|
|
106
|
+
openLinks?: boolean;
|
|
107
|
+
updateModelContext?: boolean | string[];
|
|
108
|
+
message?: boolean;
|
|
109
|
+
logging?: boolean;
|
|
110
|
+
downloadFile?: boolean;
|
|
111
|
+
sandbox?: Record<string, unknown>;
|
|
112
|
+
[key: string]: unknown;
|
|
113
|
+
}
|
|
@@ -0,0 +1,473 @@
|
|
|
1
|
+
import {
|
|
2
|
+
HOST_CONTEXT_CHANGED_METHOD,
|
|
3
|
+
HOST_CONTEXT_CHANGED_METHOD_LEGACY,
|
|
4
|
+
LOG_MESSAGE_METHOD,
|
|
5
|
+
OPEN_LINK_METHOD,
|
|
6
|
+
OPEN_LINK_METHOD_LEGACY,
|
|
7
|
+
REQUEST_DISPLAY_MODE_METHOD,
|
|
8
|
+
REQUEST_DISPLAY_MODE_METHOD_LEGACY,
|
|
9
|
+
RESOURCES_READ_METHOD,
|
|
10
|
+
SIZE_CHANGED_METHOD,
|
|
11
|
+
UI_MESSAGE_METHOD,
|
|
12
|
+
UPDATE_MODEL_CONTEXT_METHOD,
|
|
13
|
+
} from "./mcp-app-protocol";
|
|
14
|
+
import type {
|
|
15
|
+
McpHostCallToolParams,
|
|
16
|
+
McpHostCapabilities,
|
|
17
|
+
McpHostContainerDimensions,
|
|
18
|
+
McpHostContext,
|
|
19
|
+
McpHostMessageResult,
|
|
20
|
+
McpHostModelContextResult,
|
|
21
|
+
McpHostOpenLinkParams,
|
|
22
|
+
McpHostReadResourceResult,
|
|
23
|
+
McpHostRequestDisplayModeParams,
|
|
24
|
+
McpHostRequestDisplayModeResult,
|
|
25
|
+
McpHostSendMessageParams,
|
|
26
|
+
McpHostToolResult,
|
|
27
|
+
McpUiDisplayMode,
|
|
28
|
+
McpHostUpdateModelContextParams,
|
|
29
|
+
} from "./mcp-app-types";
|
|
30
|
+
|
|
31
|
+
export * from "./mcp-app-protocol";
|
|
32
|
+
export type * from "./mcp-app-types";
|
|
33
|
+
|
|
34
|
+
export interface McpHostBridgeState {
|
|
35
|
+
isConnected: boolean;
|
|
36
|
+
hostContext: McpHostContext | null;
|
|
37
|
+
hostCapabilities: McpHostCapabilities | null;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export interface McpHostBridge {
|
|
41
|
+
callTool: (
|
|
42
|
+
name: McpHostCallToolParams["name"],
|
|
43
|
+
args?: McpHostCallToolParams["arguments"]
|
|
44
|
+
) => Promise<McpHostToolResult>;
|
|
45
|
+
requestDisplayMode: (
|
|
46
|
+
mode: McpUiDisplayMode
|
|
47
|
+
) => Promise<McpHostRequestDisplayModeResult>;
|
|
48
|
+
openLink: (url: McpHostOpenLinkParams["url"]) => Promise<void>;
|
|
49
|
+
readResource: (uri: string) => Promise<McpHostReadResourceResult>;
|
|
50
|
+
sendMessage: (params: McpHostSendMessageParams) => Promise<McpHostMessageResult>;
|
|
51
|
+
updateModelContext: (
|
|
52
|
+
params: McpHostUpdateModelContextParams
|
|
53
|
+
) => Promise<McpHostModelContextResult>;
|
|
54
|
+
logMessage: (params: McpHostSendMessageParams) => Promise<void>;
|
|
55
|
+
notifySizeChanged: (
|
|
56
|
+
params: McpHostContainerDimensions
|
|
57
|
+
) => Promise<void>;
|
|
58
|
+
getState: () => McpHostBridgeState;
|
|
59
|
+
getHostContext: () => McpHostContext | null;
|
|
60
|
+
getHostCapabilities: () => McpHostCapabilities | null;
|
|
61
|
+
isConnected: () => boolean;
|
|
62
|
+
subscribe: (listener: (state: McpHostBridgeState) => void) => () => void;
|
|
63
|
+
dispose: () => void;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
interface PendingRequest {
|
|
67
|
+
resolve: (value: unknown) => void;
|
|
68
|
+
reject: (error: Error) => void;
|
|
69
|
+
timeoutId: ReturnType<typeof setTimeout>;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
interface MessageEventLike {
|
|
73
|
+
source: unknown;
|
|
74
|
+
data: unknown;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
interface MessageTargetLike {
|
|
78
|
+
postMessage: (message: unknown, targetOrigin: string) => void;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
interface WindowLike extends MessageTargetLike {
|
|
82
|
+
parent: MessageTargetLike;
|
|
83
|
+
open?: (url: string, target?: string, features?: string) => unknown;
|
|
84
|
+
addEventListener: (
|
|
85
|
+
type: "message",
|
|
86
|
+
listener: (event: MessageEventLike) => void
|
|
87
|
+
) => void;
|
|
88
|
+
removeEventListener: (
|
|
89
|
+
type: "message",
|
|
90
|
+
listener: (event: MessageEventLike) => void
|
|
91
|
+
) => void;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export interface CreateMcpHostBridgeOptions {
|
|
95
|
+
targetWindow?: WindowLike;
|
|
96
|
+
requestTimeoutMs?: number;
|
|
97
|
+
connectionTimeoutMs?: number;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function getDefaultWindow(): WindowLike | null {
|
|
101
|
+
if (typeof window === "undefined") {
|
|
102
|
+
return null;
|
|
103
|
+
}
|
|
104
|
+
return window as unknown as WindowLike;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
108
|
+
return !!value && typeof value === "object";
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function toErrorMessage(error: unknown, fallback: string): string {
|
|
112
|
+
if (error instanceof Error && error.message) {
|
|
113
|
+
return error.message;
|
|
114
|
+
}
|
|
115
|
+
return fallback;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function mergeHostContext(
|
|
119
|
+
current: McpHostContext | null,
|
|
120
|
+
incoming: McpHostContext
|
|
121
|
+
): McpHostContext {
|
|
122
|
+
const merged: McpHostContext = {
|
|
123
|
+
...(current ?? {}),
|
|
124
|
+
...incoming,
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
if (current?.safeAreaInsets || incoming.safeAreaInsets) {
|
|
128
|
+
merged.safeAreaInsets = {
|
|
129
|
+
...(current?.safeAreaInsets ?? {}),
|
|
130
|
+
...(incoming.safeAreaInsets ?? {}),
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
if (current?.containerDimensions || incoming.containerDimensions) {
|
|
135
|
+
merged.containerDimensions = {
|
|
136
|
+
...(current?.containerDimensions ?? {}),
|
|
137
|
+
...(incoming.containerDimensions ?? {}),
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
if (current?.styles || incoming.styles) {
|
|
142
|
+
merged.styles = {
|
|
143
|
+
...(current?.styles ?? {}),
|
|
144
|
+
...(incoming.styles ?? {}),
|
|
145
|
+
variables:
|
|
146
|
+
current?.styles?.variables || incoming.styles?.variables
|
|
147
|
+
? {
|
|
148
|
+
...(current?.styles?.variables ?? {}),
|
|
149
|
+
...(incoming.styles?.variables ?? {}),
|
|
150
|
+
}
|
|
151
|
+
: undefined,
|
|
152
|
+
css:
|
|
153
|
+
current?.styles?.css || incoming.styles?.css
|
|
154
|
+
? {
|
|
155
|
+
...(current?.styles?.css ?? {}),
|
|
156
|
+
...(incoming.styles?.css ?? {}),
|
|
157
|
+
}
|
|
158
|
+
: undefined,
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
return merged;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
export function createMcpHostBridge(
|
|
166
|
+
options: CreateMcpHostBridgeOptions = {}
|
|
167
|
+
): McpHostBridge {
|
|
168
|
+
const targetWindow = options.targetWindow ?? getDefaultWindow();
|
|
169
|
+
const requestTimeoutMs = options.requestTimeoutMs ?? 15_000;
|
|
170
|
+
const connectionTimeoutMs = options.connectionTimeoutMs ?? 2_000;
|
|
171
|
+
|
|
172
|
+
let nextId = 100;
|
|
173
|
+
let disposed = false;
|
|
174
|
+
let hasObservedHostTraffic = false;
|
|
175
|
+
let state: McpHostBridgeState = {
|
|
176
|
+
isConnected: !!targetWindow && targetWindow.parent !== targetWindow,
|
|
177
|
+
hostContext: null,
|
|
178
|
+
hostCapabilities: null,
|
|
179
|
+
};
|
|
180
|
+
|
|
181
|
+
const listeners = new Set<(state: McpHostBridgeState) => void>();
|
|
182
|
+
const pending = new Map<number, PendingRequest>();
|
|
183
|
+
|
|
184
|
+
const emit = () => {
|
|
185
|
+
for (const listener of listeners) {
|
|
186
|
+
listener(state);
|
|
187
|
+
}
|
|
188
|
+
};
|
|
189
|
+
|
|
190
|
+
const setState = (nextState: McpHostBridgeState) => {
|
|
191
|
+
if (
|
|
192
|
+
nextState.isConnected === state.isConnected &&
|
|
193
|
+
nextState.hostContext === state.hostContext &&
|
|
194
|
+
nextState.hostCapabilities === state.hostCapabilities
|
|
195
|
+
) {
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
state = nextState;
|
|
199
|
+
emit();
|
|
200
|
+
};
|
|
201
|
+
|
|
202
|
+
const rejectPending = (message: string) => {
|
|
203
|
+
for (const [id, request] of pending.entries()) {
|
|
204
|
+
clearTimeout(request.timeoutId);
|
|
205
|
+
request.reject(new Error(message));
|
|
206
|
+
pending.delete(id);
|
|
207
|
+
}
|
|
208
|
+
};
|
|
209
|
+
|
|
210
|
+
const applyHostUpdate = (incoming: {
|
|
211
|
+
hostContext?: McpHostContext;
|
|
212
|
+
hostCapabilities?: McpHostCapabilities;
|
|
213
|
+
}) => {
|
|
214
|
+
const nextContext = incoming.hostContext
|
|
215
|
+
? mergeHostContext(state.hostContext, incoming.hostContext)
|
|
216
|
+
: state.hostContext;
|
|
217
|
+
const nextCapabilities = incoming.hostCapabilities
|
|
218
|
+
? {
|
|
219
|
+
...(state.hostCapabilities ?? {}),
|
|
220
|
+
...incoming.hostCapabilities,
|
|
221
|
+
}
|
|
222
|
+
: state.hostCapabilities;
|
|
223
|
+
|
|
224
|
+
setState({
|
|
225
|
+
isConnected: true,
|
|
226
|
+
hostContext: nextContext,
|
|
227
|
+
hostCapabilities: nextCapabilities,
|
|
228
|
+
});
|
|
229
|
+
};
|
|
230
|
+
|
|
231
|
+
const handleMessage = (event: MessageEventLike) => {
|
|
232
|
+
if (!targetWindow || event.source !== targetWindow.parent) return;
|
|
233
|
+
if (!isRecord(event.data)) return;
|
|
234
|
+
|
|
235
|
+
hasObservedHostTraffic = true;
|
|
236
|
+
if (!state.isConnected) {
|
|
237
|
+
setState({ ...state, isConnected: true });
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
const data = event.data;
|
|
241
|
+
|
|
242
|
+
if ("id" in data && data.id != null && typeof data.id === "number") {
|
|
243
|
+
const request = pending.get(data.id);
|
|
244
|
+
if (request) {
|
|
245
|
+
clearTimeout(request.timeoutId);
|
|
246
|
+
pending.delete(data.id);
|
|
247
|
+
if (isRecord(data.error)) {
|
|
248
|
+
request.reject(
|
|
249
|
+
new Error(
|
|
250
|
+
typeof data.error.message === "string"
|
|
251
|
+
? data.error.message
|
|
252
|
+
: "MCP request failed"
|
|
253
|
+
)
|
|
254
|
+
);
|
|
255
|
+
} else {
|
|
256
|
+
request.resolve(data.result);
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
if (data.id === 1 && isRecord(data.result)) {
|
|
262
|
+
applyHostUpdate({
|
|
263
|
+
hostContext: isRecord(data.result.hostContext)
|
|
264
|
+
? (data.result.hostContext as McpHostContext)
|
|
265
|
+
: undefined,
|
|
266
|
+
hostCapabilities: isRecord(data.result.hostCapabilities)
|
|
267
|
+
? (data.result.hostCapabilities as McpHostCapabilities)
|
|
268
|
+
: undefined,
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
if (
|
|
273
|
+
data.method === HOST_CONTEXT_CHANGED_METHOD &&
|
|
274
|
+
isRecord(data.params)
|
|
275
|
+
) {
|
|
276
|
+
applyHostUpdate({
|
|
277
|
+
hostContext: data.params as McpHostContext,
|
|
278
|
+
});
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
if (
|
|
282
|
+
data.method === HOST_CONTEXT_CHANGED_METHOD_LEGACY &&
|
|
283
|
+
isRecord(data.params) &&
|
|
284
|
+
isRecord(data.params.hostContext)
|
|
285
|
+
) {
|
|
286
|
+
applyHostUpdate({
|
|
287
|
+
hostContext: data.params.hostContext as McpHostContext,
|
|
288
|
+
});
|
|
289
|
+
}
|
|
290
|
+
};
|
|
291
|
+
|
|
292
|
+
if (targetWindow) {
|
|
293
|
+
targetWindow.addEventListener("message", handleMessage);
|
|
294
|
+
|
|
295
|
+
if (targetWindow.parent !== targetWindow) {
|
|
296
|
+
setTimeout(() => {
|
|
297
|
+
if (disposed || hasObservedHostTraffic || state.hostContext) return;
|
|
298
|
+
setState({ ...state, isConnected: false });
|
|
299
|
+
}, connectionTimeoutMs);
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
const ensureWindow = (): WindowLike => {
|
|
304
|
+
if (disposed) {
|
|
305
|
+
throw new Error("MCP host bridge has been disposed");
|
|
306
|
+
}
|
|
307
|
+
if (!targetWindow) {
|
|
308
|
+
throw new Error("MCP host bridge requires a browser window");
|
|
309
|
+
}
|
|
310
|
+
return targetWindow;
|
|
311
|
+
};
|
|
312
|
+
|
|
313
|
+
const sendNotification = (method: string, params: unknown) => {
|
|
314
|
+
const activeWindow = ensureWindow();
|
|
315
|
+
activeWindow.parent.postMessage(
|
|
316
|
+
{
|
|
317
|
+
jsonrpc: "2.0",
|
|
318
|
+
method,
|
|
319
|
+
params,
|
|
320
|
+
},
|
|
321
|
+
"*"
|
|
322
|
+
);
|
|
323
|
+
};
|
|
324
|
+
|
|
325
|
+
const sendRequest = (
|
|
326
|
+
method: string,
|
|
327
|
+
params: Record<string, unknown> = {}
|
|
328
|
+
): Promise<unknown> => {
|
|
329
|
+
const activeWindow = ensureWindow();
|
|
330
|
+
|
|
331
|
+
return new Promise((resolve, reject) => {
|
|
332
|
+
const id = nextId++;
|
|
333
|
+
const timeoutId = setTimeout(() => {
|
|
334
|
+
if (!pending.has(id)) return;
|
|
335
|
+
pending.delete(id);
|
|
336
|
+
reject(new Error(`MCP request timed out: ${method}`));
|
|
337
|
+
}, requestTimeoutMs);
|
|
338
|
+
|
|
339
|
+
pending.set(id, { resolve, reject, timeoutId });
|
|
340
|
+
|
|
341
|
+
activeWindow.parent.postMessage(
|
|
342
|
+
{
|
|
343
|
+
jsonrpc: "2.0",
|
|
344
|
+
id,
|
|
345
|
+
method,
|
|
346
|
+
params,
|
|
347
|
+
},
|
|
348
|
+
"*"
|
|
349
|
+
);
|
|
350
|
+
});
|
|
351
|
+
};
|
|
352
|
+
|
|
353
|
+
const sendRequestWithFallback = async (
|
|
354
|
+
methods: string[],
|
|
355
|
+
params: Record<string, unknown>
|
|
356
|
+
) => {
|
|
357
|
+
let lastError: unknown;
|
|
358
|
+
|
|
359
|
+
for (const method of methods) {
|
|
360
|
+
try {
|
|
361
|
+
return await sendRequest(method, params);
|
|
362
|
+
} catch (error) {
|
|
363
|
+
lastError = error;
|
|
364
|
+
const message = toErrorMessage(error, "MCP request failed");
|
|
365
|
+
if (!/method not found|unknown method/i.test(message)) {
|
|
366
|
+
throw error;
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
throw lastError instanceof Error
|
|
372
|
+
? lastError
|
|
373
|
+
: new Error("MCP request failed");
|
|
374
|
+
};
|
|
375
|
+
|
|
376
|
+
const fallbackOpen = async (url: string) => {
|
|
377
|
+
if (targetWindow?.open) {
|
|
378
|
+
targetWindow.open(url, "_blank", "noopener,noreferrer");
|
|
379
|
+
return;
|
|
380
|
+
}
|
|
381
|
+
throw new Error("Unable to open link without a browser window");
|
|
382
|
+
};
|
|
383
|
+
|
|
384
|
+
return {
|
|
385
|
+
callTool(name, args) {
|
|
386
|
+
return sendRequest("tools/call", {
|
|
387
|
+
name,
|
|
388
|
+
arguments: args ?? {},
|
|
389
|
+
}) as Promise<McpHostToolResult>;
|
|
390
|
+
},
|
|
391
|
+
|
|
392
|
+
requestDisplayMode(mode) {
|
|
393
|
+
return sendRequestWithFallback(
|
|
394
|
+
[REQUEST_DISPLAY_MODE_METHOD, REQUEST_DISPLAY_MODE_METHOD_LEGACY],
|
|
395
|
+
{ mode }
|
|
396
|
+
) as Promise<McpHostRequestDisplayModeResult>;
|
|
397
|
+
},
|
|
398
|
+
|
|
399
|
+
async openLink(url) {
|
|
400
|
+
try {
|
|
401
|
+
await sendRequestWithFallback(
|
|
402
|
+
[OPEN_LINK_METHOD, OPEN_LINK_METHOD_LEGACY],
|
|
403
|
+
{ url }
|
|
404
|
+
);
|
|
405
|
+
} catch (error) {
|
|
406
|
+
const canFallback = !state.isConnected || !targetWindow;
|
|
407
|
+
if (canFallback) {
|
|
408
|
+
await fallbackOpen(url);
|
|
409
|
+
return;
|
|
410
|
+
}
|
|
411
|
+
throw new Error(toErrorMessage(error, "Failed to open link"));
|
|
412
|
+
}
|
|
413
|
+
},
|
|
414
|
+
|
|
415
|
+
readResource(uri) {
|
|
416
|
+
return sendRequest(RESOURCES_READ_METHOD, {
|
|
417
|
+
uri,
|
|
418
|
+
}) as Promise<McpHostReadResourceResult>;
|
|
419
|
+
},
|
|
420
|
+
|
|
421
|
+
sendMessage(params) {
|
|
422
|
+
return sendRequest(UI_MESSAGE_METHOD, params) as Promise<McpHostMessageResult>;
|
|
423
|
+
},
|
|
424
|
+
|
|
425
|
+
updateModelContext(params) {
|
|
426
|
+
return sendRequest(
|
|
427
|
+
UPDATE_MODEL_CONTEXT_METHOD,
|
|
428
|
+
params
|
|
429
|
+
) as Promise<McpHostModelContextResult>;
|
|
430
|
+
},
|
|
431
|
+
|
|
432
|
+
async logMessage(params) {
|
|
433
|
+
sendNotification(LOG_MESSAGE_METHOD, params);
|
|
434
|
+
},
|
|
435
|
+
|
|
436
|
+
async notifySizeChanged(params) {
|
|
437
|
+
sendNotification(SIZE_CHANGED_METHOD, params);
|
|
438
|
+
},
|
|
439
|
+
|
|
440
|
+
getState() {
|
|
441
|
+
return state;
|
|
442
|
+
},
|
|
443
|
+
|
|
444
|
+
getHostContext() {
|
|
445
|
+
return state.hostContext;
|
|
446
|
+
},
|
|
447
|
+
|
|
448
|
+
getHostCapabilities() {
|
|
449
|
+
return state.hostCapabilities;
|
|
450
|
+
},
|
|
451
|
+
|
|
452
|
+
isConnected() {
|
|
453
|
+
return state.isConnected;
|
|
454
|
+
},
|
|
455
|
+
|
|
456
|
+
subscribe(listener) {
|
|
457
|
+
listeners.add(listener);
|
|
458
|
+
return () => {
|
|
459
|
+
listeners.delete(listener);
|
|
460
|
+
};
|
|
461
|
+
},
|
|
462
|
+
|
|
463
|
+
dispose() {
|
|
464
|
+
if (disposed) return;
|
|
465
|
+
disposed = true;
|
|
466
|
+
if (targetWindow) {
|
|
467
|
+
targetWindow.removeEventListener("message", handleMessage);
|
|
468
|
+
}
|
|
469
|
+
rejectPending("MCP host bridge has been disposed");
|
|
470
|
+
listeners.clear();
|
|
471
|
+
},
|
|
472
|
+
};
|
|
473
|
+
}
|