@tech-sumit/webmcp-cdp 0.0.0-stage → 0.4.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.
@@ -0,0 +1,165 @@
1
+ import { DiscoveredTool, ToolSource, ToolSourceConfig, ToolCallResultContent } from '@tech-sumit/ai-inspector-types';
2
+ export { DiscoveredTool, ToolCallResultContent, ToolSource, ToolSourceConfig } from '@tech-sumit/ai-inspector-types';
3
+ import CDP from 'chrome-remote-interface';
4
+
5
+ /**
6
+ * Tool annotations per the WebMCP spec's `ToolAnnotations` dictionary.
7
+ * All hints default to `false` in the spec.
8
+ */
9
+ interface WebMCPToolAnnotations {
10
+ readOnlyHint?: boolean;
11
+ untrustedContentHint?: boolean;
12
+ consequentialHint?: boolean;
13
+ debugging?: boolean;
14
+ /** Chromium-only: declarative tool declared with the `toolautosubmit` attribute. */
15
+ autosubmit?: boolean;
16
+ }
17
+ /**
18
+ * A discovered tool, extending the shared `DiscoveredTool` with the fields
19
+ * the current spec's `Tool` interface and the CDP `WebMCP.Tool`
20
+ * type expose. All additions are optional, so it stays assignable to
21
+ * `DiscoveredTool`.
22
+ */
23
+ interface WebMCPDiscoveredTool extends DiscoveredTool {
24
+ /** Human-readable label (`Tool.title`). */
25
+ title?: string;
26
+ /** Full annotations (`Tool.annotations`). */
27
+ annotations?: WebMCPToolAnnotations;
28
+ /** Serialized origin of the registering document (`Tool.origin`). */
29
+ origin?: string;
30
+ /** JSON-stringified output JSON Schema (`Tool.outputSchema`), when provided. */
31
+ outputSchema?: string;
32
+ /**
33
+ * CDP `WebMCP.ToolId`: identifies this exact registration. Newer Chromium
34
+ * only; when set, execution targets it instead of the name.
35
+ */
36
+ toolId?: string;
37
+ /** CDP frame that registered the tool. */
38
+ frameId?: string;
39
+ /** Set for declarative (form-based) tools discovered via CDP. */
40
+ backendNodeId?: number;
41
+ }
42
+ /** Options for `CdpToolSource.callTool()`. */
43
+ interface CallToolOptions {
44
+ /** Aborting cancels the invocation (`WebMCP.cancelInvocation`). */
45
+ signal?: AbortSignal;
46
+ }
47
+ /** Which mechanism a target uses for tool discovery/execution. */
48
+ type DiscoveryMode = "cdp" | "document" | "testing" | "none";
49
+
50
+ /** `WebMCP.Tool` from the experimental CDP WebMCP domain. */
51
+ interface CdpWebMCPTool {
52
+ /** Opaque per-registration id (newer Chromium; absent on Chrome <= 153). */
53
+ toolId?: string;
54
+ name: string;
55
+ description: string;
56
+ inputSchema?: Record<string, unknown>;
57
+ outputSchema?: Record<string, unknown>;
58
+ annotations?: {
59
+ readOnly?: boolean;
60
+ untrustedContent?: boolean;
61
+ consequential?: boolean;
62
+ debugging?: boolean;
63
+ autosubmit?: boolean;
64
+ };
65
+ frameId: string;
66
+ backendNodeId?: number;
67
+ }
68
+ /**
69
+ * Map a CDP `WebMCP.Tool` to a discovered tool. `origin` is the registering
70
+ * frame's security origin, which `WebMCP.Tool` itself does not carry.
71
+ */
72
+ declare function fromCdpTool(t: CdpWebMCPTool, origin?: string): WebMCPDiscoveredTool;
73
+ /**
74
+ * A ToolSource that discovers and executes WebMCP tools via Chrome DevTools Protocol.
75
+ *
76
+ * Uses `chrome-remote-interface` to connect to Chrome instances with
77
+ * `--remote-debugging-port`.
78
+ *
79
+ * Discovery prefers Chromium's native CDP `WebMCP` domain (`WebMCP.enable`,
80
+ * `toolsAdded`/`toolsRemoved`, `invokeTool`/`toolResponded`). When the
81
+ * domain is unavailable it falls back to page script via `Runtime.evaluate`:
82
+ * the spec's `document.modelContext.getTools()`/`executeTool()` with the
83
+ * `toolchange` event, or the legacy `navigator.modelContextTesting` API on
84
+ * older Chrome builds.
85
+ */
86
+ declare class CdpToolSource implements ToolSource {
87
+ private targetManager;
88
+ private changeListeners;
89
+ private connected;
90
+ private config;
91
+ /** Native-mode tools per target, keyed by {@link cdpToolKey}. */
92
+ private cdpTools;
93
+ private pendingInvocations;
94
+ /** `toolResponded` events that arrived before `invokeTool` returned. */
95
+ private earlyResponses;
96
+ /** Invocations the caller aborted; their late `toolResponded` is dropped. */
97
+ private abortedInvocations;
98
+ connect(config?: ToolSourceConfig): Promise<void>;
99
+ /**
100
+ * The fallback discovery script injected into each page context.
101
+ * Subscribes to tool changes so they trigger the `__webmcpToolsChanged`
102
+ * binding, and resolves to `{ mode, tools }` as a JSON string.
103
+ */
104
+ static readonly DISCOVERY_SCRIPT = "(async () => {\n const mc = document.modelContext;\n if (mc && typeof mc.getTools === \"function\") {\n const mapTool = (t) => ({\n name: t.name,\n description: t.description,\n // Spec: object. Chrome 153 still returns the JSON string.\n inputSchema: t.inputSchema == null ? \"\" : typeof t.inputSchema === \"string\" ? t.inputSchema : JSON.stringify(t.inputSchema),\n ...(t.outputSchema != null ? { outputSchema: typeof t.outputSchema === \"string\" ? t.outputSchema : JSON.stringify(t.outputSchema) } : {}),\n ...(t.title ? { title: t.title } : {}),\n ...(t.origin ? { origin: t.origin } : {}),\n ...(t.annotations ? { annotations: t.annotations, readOnlyHint: !!t.annotations.readOnlyHint } : {}),\n });\n const list = async () => (await mc.getTools()).map(mapTool);\n if (!window.__webmcpCdpSubscribed) {\n window.__webmcpCdpSubscribed = true;\n mc.addEventListener(\"toolchange\", async () => {\n __webmcpToolsChanged(JSON.stringify(await list()));\n });\n }\n return JSON.stringify({ mode: \"document\", tools: await list() });\n }\n const mct = navigator.modelContextTesting;\n if (mct) {\n const mapTool = (t) => ({\n name: t.name,\n description: t.description,\n inputSchema: t.inputSchema,\n ...(t.readOnlyHint != null ? { readOnlyHint: t.readOnlyHint } : {}),\n });\n mct.registerToolsChangedCallback(() => {\n __webmcpToolsChanged(JSON.stringify(mct.listTools().map(mapTool)));\n });\n return JSON.stringify({ mode: \"testing\", tools: mct.listTools().map(mapTool) });\n }\n return JSON.stringify({ mode: \"none\", tools: [] });\n })()";
105
+ /** Build the fallback execution expression for a page. */
106
+ static executeScript(mode: DiscoveryMode, name: string, inputArguments: string): string;
107
+ /** Try to enable the native CDP WebMCP domain. Returns false if unsupported. */
108
+ private enableCdpDomain;
109
+ private settleInvocation;
110
+ /** Run the fallback discovery script and return its result. */
111
+ private runDiscovery;
112
+ private attachToTarget;
113
+ listTools(): WebMCPDiscoveredTool[];
114
+ /**
115
+ * Execute a tool by name.
116
+ *
117
+ * With the CDP WebMCP domain this calls `WebMCP.invokeTool` and waits for
118
+ * the matching `WebMCP.toolResponded` event. Otherwise it evaluates
119
+ * `document.modelContext.executeTool()` (or the legacy
120
+ * `navigator.modelContextTesting.executeTool()`) in the page.
121
+ *
122
+ * @param name - Tool name
123
+ * @param inputArguments - JSON-encoded input object
124
+ * @param options - Optional `signal` to cancel the invocation
125
+ * @returns Array of content blocks (text results from WebMCP tool execution)
126
+ */
127
+ callTool(name: string, inputArguments: string, options?: CallToolOptions): Promise<ToolCallResultContent[]>;
128
+ private invokeViaCdp;
129
+ onToolsChanged(cb: (tools: WebMCPDiscoveredTool[]) => void): void;
130
+ disconnect(): Promise<void>;
131
+ /** Whether the source is currently connected. */
132
+ isConnected(): boolean;
133
+ private notifyChange;
134
+ }
135
+
136
+ interface ManagedTarget {
137
+ id: string;
138
+ url: string;
139
+ title: string;
140
+ client: CDP.Client;
141
+ tools: WebMCPDiscoveredTool[];
142
+ /** How tools are discovered/executed in this target (defaults to "none"). */
143
+ mode?: DiscoveryMode;
144
+ }
145
+ /**
146
+ * Manages CDP targets (tabs) and their associated tools.
147
+ * Handles multi-tab discovery, tracking which tools belong to which tab.
148
+ */
149
+ declare class TargetManager {
150
+ private targets;
151
+ add(target: ManagedTarget): void;
152
+ remove(id: string): ManagedTarget | undefined;
153
+ get(id: string): ManagedTarget | undefined;
154
+ updateTools(id: string, tools: WebMCPDiscoveredTool[]): void;
155
+ /** Get all tools from all connected targets. */
156
+ allTools(): WebMCPDiscoveredTool[];
157
+ /** Find which target owns a tool by name. */
158
+ findTargetForTool(name: string): ManagedTarget | undefined;
159
+ /** Get all target IDs. */
160
+ ids(): string[];
161
+ /** Disconnect all clients and clear state. */
162
+ disconnectAll(): Promise<void>;
163
+ }
164
+
165
+ export { type CallToolOptions, CdpToolSource, type DiscoveryMode, type ManagedTarget, TargetManager, type WebMCPDiscoveredTool, type WebMCPToolAnnotations, fromCdpTool };
@@ -0,0 +1,165 @@
1
+ import { DiscoveredTool, ToolSource, ToolSourceConfig, ToolCallResultContent } from '@tech-sumit/ai-inspector-types';
2
+ export { DiscoveredTool, ToolCallResultContent, ToolSource, ToolSourceConfig } from '@tech-sumit/ai-inspector-types';
3
+ import CDP from 'chrome-remote-interface';
4
+
5
+ /**
6
+ * Tool annotations per the WebMCP spec's `ToolAnnotations` dictionary.
7
+ * All hints default to `false` in the spec.
8
+ */
9
+ interface WebMCPToolAnnotations {
10
+ readOnlyHint?: boolean;
11
+ untrustedContentHint?: boolean;
12
+ consequentialHint?: boolean;
13
+ debugging?: boolean;
14
+ /** Chromium-only: declarative tool declared with the `toolautosubmit` attribute. */
15
+ autosubmit?: boolean;
16
+ }
17
+ /**
18
+ * A discovered tool, extending the shared `DiscoveredTool` with the fields
19
+ * the current spec's `Tool` interface and the CDP `WebMCP.Tool`
20
+ * type expose. All additions are optional, so it stays assignable to
21
+ * `DiscoveredTool`.
22
+ */
23
+ interface WebMCPDiscoveredTool extends DiscoveredTool {
24
+ /** Human-readable label (`Tool.title`). */
25
+ title?: string;
26
+ /** Full annotations (`Tool.annotations`). */
27
+ annotations?: WebMCPToolAnnotations;
28
+ /** Serialized origin of the registering document (`Tool.origin`). */
29
+ origin?: string;
30
+ /** JSON-stringified output JSON Schema (`Tool.outputSchema`), when provided. */
31
+ outputSchema?: string;
32
+ /**
33
+ * CDP `WebMCP.ToolId`: identifies this exact registration. Newer Chromium
34
+ * only; when set, execution targets it instead of the name.
35
+ */
36
+ toolId?: string;
37
+ /** CDP frame that registered the tool. */
38
+ frameId?: string;
39
+ /** Set for declarative (form-based) tools discovered via CDP. */
40
+ backendNodeId?: number;
41
+ }
42
+ /** Options for `CdpToolSource.callTool()`. */
43
+ interface CallToolOptions {
44
+ /** Aborting cancels the invocation (`WebMCP.cancelInvocation`). */
45
+ signal?: AbortSignal;
46
+ }
47
+ /** Which mechanism a target uses for tool discovery/execution. */
48
+ type DiscoveryMode = "cdp" | "document" | "testing" | "none";
49
+
50
+ /** `WebMCP.Tool` from the experimental CDP WebMCP domain. */
51
+ interface CdpWebMCPTool {
52
+ /** Opaque per-registration id (newer Chromium; absent on Chrome <= 153). */
53
+ toolId?: string;
54
+ name: string;
55
+ description: string;
56
+ inputSchema?: Record<string, unknown>;
57
+ outputSchema?: Record<string, unknown>;
58
+ annotations?: {
59
+ readOnly?: boolean;
60
+ untrustedContent?: boolean;
61
+ consequential?: boolean;
62
+ debugging?: boolean;
63
+ autosubmit?: boolean;
64
+ };
65
+ frameId: string;
66
+ backendNodeId?: number;
67
+ }
68
+ /**
69
+ * Map a CDP `WebMCP.Tool` to a discovered tool. `origin` is the registering
70
+ * frame's security origin, which `WebMCP.Tool` itself does not carry.
71
+ */
72
+ declare function fromCdpTool(t: CdpWebMCPTool, origin?: string): WebMCPDiscoveredTool;
73
+ /**
74
+ * A ToolSource that discovers and executes WebMCP tools via Chrome DevTools Protocol.
75
+ *
76
+ * Uses `chrome-remote-interface` to connect to Chrome instances with
77
+ * `--remote-debugging-port`.
78
+ *
79
+ * Discovery prefers Chromium's native CDP `WebMCP` domain (`WebMCP.enable`,
80
+ * `toolsAdded`/`toolsRemoved`, `invokeTool`/`toolResponded`). When the
81
+ * domain is unavailable it falls back to page script via `Runtime.evaluate`:
82
+ * the spec's `document.modelContext.getTools()`/`executeTool()` with the
83
+ * `toolchange` event, or the legacy `navigator.modelContextTesting` API on
84
+ * older Chrome builds.
85
+ */
86
+ declare class CdpToolSource implements ToolSource {
87
+ private targetManager;
88
+ private changeListeners;
89
+ private connected;
90
+ private config;
91
+ /** Native-mode tools per target, keyed by {@link cdpToolKey}. */
92
+ private cdpTools;
93
+ private pendingInvocations;
94
+ /** `toolResponded` events that arrived before `invokeTool` returned. */
95
+ private earlyResponses;
96
+ /** Invocations the caller aborted; their late `toolResponded` is dropped. */
97
+ private abortedInvocations;
98
+ connect(config?: ToolSourceConfig): Promise<void>;
99
+ /**
100
+ * The fallback discovery script injected into each page context.
101
+ * Subscribes to tool changes so they trigger the `__webmcpToolsChanged`
102
+ * binding, and resolves to `{ mode, tools }` as a JSON string.
103
+ */
104
+ static readonly DISCOVERY_SCRIPT = "(async () => {\n const mc = document.modelContext;\n if (mc && typeof mc.getTools === \"function\") {\n const mapTool = (t) => ({\n name: t.name,\n description: t.description,\n // Spec: object. Chrome 153 still returns the JSON string.\n inputSchema: t.inputSchema == null ? \"\" : typeof t.inputSchema === \"string\" ? t.inputSchema : JSON.stringify(t.inputSchema),\n ...(t.outputSchema != null ? { outputSchema: typeof t.outputSchema === \"string\" ? t.outputSchema : JSON.stringify(t.outputSchema) } : {}),\n ...(t.title ? { title: t.title } : {}),\n ...(t.origin ? { origin: t.origin } : {}),\n ...(t.annotations ? { annotations: t.annotations, readOnlyHint: !!t.annotations.readOnlyHint } : {}),\n });\n const list = async () => (await mc.getTools()).map(mapTool);\n if (!window.__webmcpCdpSubscribed) {\n window.__webmcpCdpSubscribed = true;\n mc.addEventListener(\"toolchange\", async () => {\n __webmcpToolsChanged(JSON.stringify(await list()));\n });\n }\n return JSON.stringify({ mode: \"document\", tools: await list() });\n }\n const mct = navigator.modelContextTesting;\n if (mct) {\n const mapTool = (t) => ({\n name: t.name,\n description: t.description,\n inputSchema: t.inputSchema,\n ...(t.readOnlyHint != null ? { readOnlyHint: t.readOnlyHint } : {}),\n });\n mct.registerToolsChangedCallback(() => {\n __webmcpToolsChanged(JSON.stringify(mct.listTools().map(mapTool)));\n });\n return JSON.stringify({ mode: \"testing\", tools: mct.listTools().map(mapTool) });\n }\n return JSON.stringify({ mode: \"none\", tools: [] });\n })()";
105
+ /** Build the fallback execution expression for a page. */
106
+ static executeScript(mode: DiscoveryMode, name: string, inputArguments: string): string;
107
+ /** Try to enable the native CDP WebMCP domain. Returns false if unsupported. */
108
+ private enableCdpDomain;
109
+ private settleInvocation;
110
+ /** Run the fallback discovery script and return its result. */
111
+ private runDiscovery;
112
+ private attachToTarget;
113
+ listTools(): WebMCPDiscoveredTool[];
114
+ /**
115
+ * Execute a tool by name.
116
+ *
117
+ * With the CDP WebMCP domain this calls `WebMCP.invokeTool` and waits for
118
+ * the matching `WebMCP.toolResponded` event. Otherwise it evaluates
119
+ * `document.modelContext.executeTool()` (or the legacy
120
+ * `navigator.modelContextTesting.executeTool()`) in the page.
121
+ *
122
+ * @param name - Tool name
123
+ * @param inputArguments - JSON-encoded input object
124
+ * @param options - Optional `signal` to cancel the invocation
125
+ * @returns Array of content blocks (text results from WebMCP tool execution)
126
+ */
127
+ callTool(name: string, inputArguments: string, options?: CallToolOptions): Promise<ToolCallResultContent[]>;
128
+ private invokeViaCdp;
129
+ onToolsChanged(cb: (tools: WebMCPDiscoveredTool[]) => void): void;
130
+ disconnect(): Promise<void>;
131
+ /** Whether the source is currently connected. */
132
+ isConnected(): boolean;
133
+ private notifyChange;
134
+ }
135
+
136
+ interface ManagedTarget {
137
+ id: string;
138
+ url: string;
139
+ title: string;
140
+ client: CDP.Client;
141
+ tools: WebMCPDiscoveredTool[];
142
+ /** How tools are discovered/executed in this target (defaults to "none"). */
143
+ mode?: DiscoveryMode;
144
+ }
145
+ /**
146
+ * Manages CDP targets (tabs) and their associated tools.
147
+ * Handles multi-tab discovery, tracking which tools belong to which tab.
148
+ */
149
+ declare class TargetManager {
150
+ private targets;
151
+ add(target: ManagedTarget): void;
152
+ remove(id: string): ManagedTarget | undefined;
153
+ get(id: string): ManagedTarget | undefined;
154
+ updateTools(id: string, tools: WebMCPDiscoveredTool[]): void;
155
+ /** Get all tools from all connected targets. */
156
+ allTools(): WebMCPDiscoveredTool[];
157
+ /** Find which target owns a tool by name. */
158
+ findTargetForTool(name: string): ManagedTarget | undefined;
159
+ /** Get all target IDs. */
160
+ ids(): string[];
161
+ /** Disconnect all clients and clear state. */
162
+ disconnectAll(): Promise<void>;
163
+ }
164
+
165
+ export { type CallToolOptions, CdpToolSource, type DiscoveryMode, type ManagedTarget, TargetManager, type WebMCPDiscoveredTool, type WebMCPToolAnnotations, fromCdpTool };