@gtkx/mcp 0.21.0 → 1.0.0-rc.2

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.
Files changed (73) hide show
  1. package/README.md +137 -34
  2. package/bin/gtkx-mcp.js +9 -1
  3. package/dist/app-router.d.ts +35 -0
  4. package/dist/app-router.d.ts.map +1 -0
  5. package/dist/app-router.js +143 -0
  6. package/dist/app-router.js.map +1 -0
  7. package/dist/connection-registry.d.ts +12 -0
  8. package/dist/connection-registry.d.ts.map +1 -0
  9. package/dist/connection-registry.js +39 -0
  10. package/dist/connection-registry.js.map +1 -0
  11. package/dist/internal.d.ts +4 -0
  12. package/dist/internal.d.ts.map +1 -0
  13. package/dist/internal.js +4 -0
  14. package/dist/internal.js.map +1 -0
  15. package/dist/protocol/errors.d.ts +25 -87
  16. package/dist/protocol/errors.d.ts.map +1 -1
  17. package/dist/protocol/errors.js +38 -101
  18. package/dist/protocol/errors.js.map +1 -1
  19. package/dist/protocol/schemas.d.ts +93 -0
  20. package/dist/protocol/schemas.d.ts.map +1 -0
  21. package/dist/protocol/schemas.js +63 -0
  22. package/dist/protocol/schemas.js.map +1 -0
  23. package/dist/reference.d.ts +13 -0
  24. package/dist/reference.d.ts.map +1 -0
  25. package/dist/reference.js +293 -0
  26. package/dist/reference.js.map +1 -0
  27. package/dist/server.d.ts +14 -0
  28. package/dist/server.d.ts.map +1 -0
  29. package/dist/server.js +244 -0
  30. package/dist/server.js.map +1 -0
  31. package/dist/socket-server.d.ts +5 -38
  32. package/dist/socket-server.d.ts.map +1 -1
  33. package/dist/socket-server.js +36 -108
  34. package/dist/socket-server.js.map +1 -1
  35. package/dist/tool.d.ts +22 -0
  36. package/dist/tool.d.ts.map +1 -0
  37. package/dist/tool.js +40 -0
  38. package/dist/tool.js.map +1 -0
  39. package/dist/transport.d.ts +49 -0
  40. package/dist/transport.d.ts.map +1 -0
  41. package/dist/transport.js +152 -0
  42. package/dist/transport.js.map +1 -0
  43. package/package.json +15 -11
  44. package/src/app-router.ts +209 -0
  45. package/src/connection-registry.ts +57 -0
  46. package/src/internal.ts +17 -0
  47. package/src/protocol/errors.ts +67 -110
  48. package/src/protocol/schemas.ts +173 -0
  49. package/src/reference.ts +449 -0
  50. package/src/server.ts +334 -0
  51. package/src/socket-server.ts +46 -147
  52. package/src/tool.ts +73 -0
  53. package/src/transport.ts +242 -0
  54. package/dist/cli.d.ts +0 -3
  55. package/dist/cli.d.ts.map +0 -1
  56. package/dist/cli.js +0 -399
  57. package/dist/cli.js.map +0 -1
  58. package/dist/connection-manager.d.ts +0 -48
  59. package/dist/connection-manager.d.ts.map +0 -1
  60. package/dist/connection-manager.js +0 -185
  61. package/dist/connection-manager.js.map +0 -1
  62. package/dist/index.d.ts +0 -5
  63. package/dist/index.d.ts.map +0 -1
  64. package/dist/index.js +0 -5
  65. package/dist/index.js.map +0 -1
  66. package/dist/protocol/types.d.ts +0 -132
  67. package/dist/protocol/types.d.ts.map +0 -1
  68. package/dist/protocol/types.js +0 -46
  69. package/dist/protocol/types.js.map +0 -1
  70. package/src/cli.ts +0 -449
  71. package/src/connection-manager.ts +0 -247
  72. package/src/index.ts +0 -27
  73. package/src/protocol/types.ts +0 -153
package/src/server.ts ADDED
@@ -0,0 +1,334 @@
1
+ import { createLogger, installGracefulShutdown, type Logger } from "@gtkx/utils";
2
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
4
+ import { createRequire } from "node:module";
5
+ import { z } from "zod";
6
+ import type { ConnectionErrorEvent } from "./transport.js";
7
+ import { type AppRegisteredEvent, AppRouter, type AppUnregisteredEvent } from "./app-router.js";
8
+ import { ConnectionRegistry } from "./connection-registry.js";
9
+ import {
10
+ type AppInfo,
11
+ DEFAULT_SOCKET_PATH,
12
+ fireEventParams,
13
+ queryParams,
14
+ screenshotParams,
15
+ treeParams,
16
+ typeParams,
17
+ widgetIdParams,
18
+ } from "./protocol/schemas.js";
19
+ import { buildReferenceTools, createReferenceProvider, registerReferenceResources } from "./reference.js";
20
+ import { SocketServer } from "./socket-server.js";
21
+ import { defineTool, imageContent, registerTool, textContent, type Tool } from "./tool.js";
22
+
23
+ type CreateMcpServerOptions = {
24
+ socketPath?: string;
25
+ version: string;
26
+ };
27
+
28
+ type McpServerHandle = {
29
+ start(): Promise<void>;
30
+ stop(): Promise<void>;
31
+ };
32
+
33
+ type AppWindow = { id: string; title: string | null };
34
+ type AppWithWindows = AppInfo & { windows?: AppWindow[] };
35
+
36
+ const require = createRequire(import.meta.url);
37
+ const { version } = require("../package.json") as { version: string };
38
+ const log: Logger = createLogger("mcp");
39
+ const APPLICATION_ID_DESCRIPTION = "Application ID to query. If not specified, uses the first connected app.";
40
+
41
+ const WIDGET_ID_DESCRIPTION =
42
+ "Widget ID obtained from `gtkx_get_widget_tree`, `gtkx_query_widgets`, or `gtkx_get_widget_props`. " +
43
+ "IDs are scoped to a single app. An ID stays valid for as long as its widget is mounted and stops " +
44
+ "resolving once the widget is unmounted.";
45
+
46
+ const applicationIdShape = { applicationId: z.string().optional().describe(APPLICATION_ID_DESCRIPTION) };
47
+
48
+ const widgetIdShape = {
49
+ ...applicationIdShape,
50
+ widgetId: widgetIdParams.shape.widgetId.describe(WIDGET_ID_DESCRIPTION),
51
+ };
52
+
53
+ const treeShape = {
54
+ ...applicationIdShape,
55
+ rootId: treeParams.shape.rootId.describe(
56
+ "Render only the subtree rooted at this widget ID (from a prior tree or query). Omit for the whole app.",
57
+ ),
58
+ maxDepth: treeParams.shape.maxDepth.describe(
59
+ "Limit how many levels deep to render; deeper descendants are summarized with a count. " +
60
+ "Combine with rootId to drill in without dumping the whole tree.",
61
+ ),
62
+ };
63
+
64
+ const listAppsShape = {
65
+ waitForApps: z
66
+ .boolean()
67
+ .optional()
68
+ .describe(
69
+ "If true, wait for at least one app to register before returning. Useful when app is still starting.",
70
+ ),
71
+ timeout: z.number().optional().describe("Timeout in milliseconds when waitForApps is true (default: 10000)"),
72
+ };
73
+
74
+ const queryWidgetsShape = {
75
+ ...applicationIdShape,
76
+ by: queryParams.shape.by.describe("Query type"),
77
+ value: queryParams.shape.value.describe("Value to search for"),
78
+ options: queryParams.shape.options.describe("Additional query options"),
79
+ };
80
+
81
+ const typeShape = {
82
+ ...widgetIdShape,
83
+ text: typeParams.shape.text.describe("Text to type"),
84
+ clear: typeParams.shape.clear.describe("Clear existing text before typing"),
85
+ };
86
+
87
+ const fireEventShape = {
88
+ ...widgetIdShape,
89
+ signal: fireEventParams.shape.signal.describe("GTK4 signal name to emit"),
90
+ args: fireEventParams.shape.args.describe("Arguments to pass to the signal"),
91
+ };
92
+
93
+ const screenshotShape = {
94
+ ...applicationIdShape,
95
+ windowId: screenshotParams.shape.windowId.describe(
96
+ "Window ID to capture. If not specified, captures the first window.",
97
+ ),
98
+ path: screenshotParams.shape.path.describe(
99
+ "Absolute path to write the PNG to on the app's machine. If set, the screenshot is saved there " +
100
+ "in addition to being returned.",
101
+ ),
102
+ };
103
+
104
+ const logSocketError = (event: Event): void => {
105
+ const error = (event as ConnectionErrorEvent).detail;
106
+ const code = (error as NodeJS.ErrnoException).code;
107
+
108
+ if (code === "EPIPE" || code === "ECONNRESET") {
109
+ return;
110
+ }
111
+
112
+ log.error(`socket error: ${error.message}`);
113
+ };
114
+
115
+ const appWithWindows = async (appRouter: AppRouter, app: AppInfo): Promise<AppWithWindows> => {
116
+ try {
117
+ const result = await appRouter.sendToApp<{ windows: AppWindow[] }>(
118
+ app.applicationId,
119
+ "app.getWindows",
120
+ {},
121
+ );
122
+
123
+ return { ...app, windows: result.windows };
124
+ } catch {
125
+ return app;
126
+ }
127
+ };
128
+
129
+ const listAppsTool = (appRouter: AppRouter): Tool =>
130
+ defineTool({
131
+ name: "gtkx_list_apps",
132
+ title: "List apps",
133
+ kind: "readOnly",
134
+ description: "List all connected GTKX applications and their open windows.",
135
+ inputSchema: listAppsShape,
136
+ handler: async ({ waitForApps, timeout }) => {
137
+ if (waitForApps && !appRouter.hasConnectedApps()) {
138
+ await appRouter.waitForApp(timeout);
139
+ }
140
+
141
+ const apps = appRouter.getApps();
142
+ const appsWithWindows = await Promise.all(apps.map((app) => appWithWindows(appRouter, app)));
143
+
144
+ return textContent(JSON.stringify(appsWithWindows, null, 2));
145
+ },
146
+ });
147
+
148
+ const screenshotTool = (appRouter: AppRouter): Tool =>
149
+ defineTool({
150
+ name: "gtkx_take_screenshot",
151
+ title: "Take screenshot",
152
+ kind: "readOnly",
153
+ description:
154
+ "Capture a screenshot of a window. Returns base64-encoded PNG image data, and optionally writes " +
155
+ "the PNG to `path` on the app's machine. You can't target widgets from a screenshot; use " +
156
+ "`gtkx_get_widget_tree` to find widget IDs for interaction.",
157
+ inputSchema: screenshotShape,
158
+ handler: async ({ applicationId, ...params }) => {
159
+ const result = await appRouter.sendToApp<{ data: string; mimeType: string; savedPath?: string }>(
160
+ applicationId,
161
+ "widget.screenshot",
162
+ params,
163
+ );
164
+
165
+ if (result.savedPath) {
166
+ return {
167
+ content: [
168
+ { type: "text", text: `Screenshot saved to ${result.savedPath}` },
169
+ { type: "image", data: result.data, mimeType: result.mimeType },
170
+ ],
171
+ };
172
+ }
173
+
174
+ return imageContent(result.data, result.mimeType);
175
+ },
176
+ });
177
+
178
+ function buildInspectionTools(appRouter: AppRouter): Tool[] {
179
+ return [
180
+ listAppsTool(appRouter),
181
+ defineTool({
182
+ name: "gtkx_get_widget_tree",
183
+ title: "Widget tree",
184
+ kind: "readOnly",
185
+ description:
186
+ "Get the widget hierarchy for a connected GTKX app. Returns a tree of widgets with their IDs, " +
187
+ "types, roles, and properties. For large apps, pass `maxDepth` for a shallow overview and/or " +
188
+ "`rootId` to render just one subtree instead of the whole (possibly truncated) tree.",
189
+ inputSchema: treeShape,
190
+ handler: async ({ applicationId, rootId, maxDepth }) => {
191
+ const result = await appRouter.sendToApp<{ tree: string }>(applicationId, "widget.getTree", {
192
+ rootId,
193
+ maxDepth,
194
+ });
195
+
196
+ return textContent(result.tree);
197
+ },
198
+ }),
199
+ defineTool({
200
+ name: "gtkx_query_widgets",
201
+ title: "Query widgets",
202
+ kind: "readOnly",
203
+ description:
204
+ "Find widgets by role, text, name, or label. Returns matching widgets with their IDs and properties.",
205
+ inputSchema: queryWidgetsShape,
206
+ handler: async ({ applicationId, ...params }) => {
207
+ const result = await appRouter.sendToApp(applicationId, "widget.query", params);
208
+
209
+ return textContent(JSON.stringify(result, null, 2));
210
+ },
211
+ }),
212
+ defineTool({
213
+ name: "gtkx_get_widget_props",
214
+ title: "Get widget properties",
215
+ kind: "readOnly",
216
+ description:
217
+ "Get a fixed summary of one widget by ID: type, accessible role, name, text, sensitivity, " +
218
+ "visibility, CSS classes, and the full subtree of descendant widgets. It does not return " +
219
+ "arbitrary GObject properties.",
220
+ inputSchema: widgetIdShape,
221
+ handler: async ({ applicationId, ...params }) => {
222
+ const result = await appRouter.sendToApp(applicationId, "widget.getProps", params);
223
+
224
+ return textContent(JSON.stringify(result, null, 2));
225
+ },
226
+ }),
227
+ screenshotTool(appRouter),
228
+ ];
229
+ }
230
+
231
+ function buildInteractionTools(appRouter: AppRouter): Tool[] {
232
+ return [
233
+ defineTool({
234
+ name: "gtkx_click",
235
+ title: "Click widget",
236
+ kind: "action",
237
+ description: "Click a widget. Works with buttons, checkboxes, and other interactive widgets.",
238
+ inputSchema: widgetIdShape,
239
+ handler: async ({ applicationId, ...params }) => {
240
+ await appRouter.sendToApp(applicationId, "widget.click", params);
241
+
242
+ return textContent("Clicked");
243
+ },
244
+ }),
245
+ defineTool({
246
+ name: "gtkx_type",
247
+ title: "Type text",
248
+ kind: "action",
249
+ description: "Type text into an editable widget like Entry or TextView",
250
+ inputSchema: typeShape,
251
+ handler: async ({ applicationId, ...params }) => {
252
+ await appRouter.sendToApp(applicationId, "widget.type", params);
253
+
254
+ return textContent("Typed text");
255
+ },
256
+ }),
257
+ defineTool({
258
+ name: "gtkx_fire_event",
259
+ title: "Fire event",
260
+ kind: "action",
261
+ description: "Emit a GTK4 signal on a widget. Use this for custom interactions.",
262
+ inputSchema: fireEventShape,
263
+ handler: async ({ applicationId, ...params }) => {
264
+ await appRouter.sendToApp(applicationId, "widget.fireEvent", params);
265
+
266
+ return textContent("Fired event");
267
+ },
268
+ }),
269
+ ];
270
+ }
271
+
272
+ function buildTools(appRouter: AppRouter): Tool[] {
273
+ return [...buildInspectionTools(appRouter), ...buildInteractionTools(appRouter)];
274
+ }
275
+
276
+ const createMcpServer = (options: CreateMcpServerOptions): McpServerHandle => {
277
+ const socketPath = options.socketPath ?? DEFAULT_SOCKET_PATH;
278
+ const registry = new ConnectionRegistry();
279
+ const socketServer = new SocketServer(registry, socketPath);
280
+ const appRouter = new AppRouter(registry);
281
+ registry.addEventListener("error", logSocketError);
282
+
283
+ appRouter.addEventListener("appRegistered", (event) => {
284
+ const appInfo = (event as AppRegisteredEvent).detail;
285
+ log.info(`app registered: ${appInfo.applicationId} (PID: ${String(appInfo.pid)})`);
286
+ });
287
+
288
+ appRouter.addEventListener("appUnregistered", (event) => {
289
+ log.info(`app unregistered: ${(event as AppUnregisteredEvent).detail}`);
290
+ });
291
+
292
+ const mcpServer = new McpServer({ name: "gtkx-mcp", version: options.version });
293
+ const referenceProvider = createReferenceProvider(() => appRouter.getProjectRoot() ?? process.cwd());
294
+
295
+ for (const tool of [...buildTools(appRouter), ...buildReferenceTools(referenceProvider)]) {
296
+ registerTool(mcpServer, tool);
297
+ }
298
+
299
+ registerReferenceResources(mcpServer, referenceProvider);
300
+ let isStopped = false;
301
+
302
+ const stop = async (): Promise<void> => {
303
+ if (isStopped) {
304
+ return;
305
+ }
306
+
307
+ isStopped = true;
308
+ await socketServer.stop();
309
+ await mcpServer.close();
310
+ };
311
+
312
+ const start = async (): Promise<void> => {
313
+ await socketServer.start();
314
+ log.info(`socket server listening on ${socketPath}`);
315
+ const transport = new StdioServerTransport();
316
+ process.stdin.on("end", () => void stop());
317
+ process.stdin.on("close", () => void stop());
318
+ await mcpServer.connect(transport);
319
+ };
320
+
321
+ return { start, stop };
322
+ };
323
+
324
+ async function main(): Promise<void> {
325
+ const server = createMcpServer({ version });
326
+
327
+ installGracefulShutdown({
328
+ onSignal: () => server.stop(),
329
+ });
330
+
331
+ await server.start();
332
+ }
333
+
334
+ export { log, createMcpServer, main };
@@ -1,65 +1,46 @@
1
- import EventEmitter from "node:events";
2
1
  import * as fs from "node:fs";
3
2
  import * as net from "node:net";
4
- import { invalidRequestError } from "./protocol/errors.js";
5
- import {
6
- DEFAULT_SOCKET_PATH,
7
- type IpcMessage,
8
- type IpcRequest,
9
- IpcRequestSchema,
10
- type IpcResponse,
11
- IpcResponseSchema,
12
- } from "./protocol/types.js";
13
-
14
- type SocketServerEventMap = {
15
- connection: [AppConnection];
16
- disconnection: [AppConnection];
17
- request: [AppConnection, IpcRequest];
18
- response: [AppConnection, IpcResponse];
19
- error: [Error];
20
- };
3
+ import type { ConnectionRegistry } from "./connection-registry.js";
4
+ import { DEFAULT_SOCKET_PATH } from "./protocol/schemas.js";
5
+ import { connectionErrorEvent } from "./transport.js";
21
6
 
22
- /**
23
- * Represents a connected application.
24
- */
25
- export type AppConnection = {
26
- /** Unique connection identifier */
27
- id: string;
28
- /** The underlying socket */
29
- socket: net.Socket;
30
- /** Buffer for incomplete messages */
31
- buffer: string;
32
- };
7
+ const socketIsLive = (socketPath: string): Promise<boolean> =>
8
+ new Promise((resolve) => {
9
+ const probe = net.connect(socketPath);
33
10
 
34
- /**
35
- * Unix domain socket server for MCP communication.
36
- *
37
- * Manages connections from GTKX applications and handles IPC messaging.
38
- */
39
- export class SocketServer extends EventEmitter<SocketServerEventMap> {
40
- private server: net.Server | null = null;
41
- private connections: Map<string, AppConnection> = new Map();
42
- private socketPath: string;
11
+ probe.once("connect", () => {
12
+ probe.destroy();
13
+ resolve(true);
14
+ });
43
15
 
44
- constructor(socketPath: string = DEFAULT_SOCKET_PATH) {
45
- super();
46
- this.socketPath = socketPath;
47
- }
16
+ probe.once("error", () => {
17
+ resolve(false);
18
+ });
19
+ });
48
20
 
49
- get path(): string {
50
- return this.socketPath;
21
+ const removeStaleSocket = async (socketPath: string): Promise<void> => {
22
+ if (!fs.existsSync(socketPath)) {
23
+ return;
51
24
  }
52
25
 
53
- get isListening(): boolean {
54
- return this.server?.listening ?? false;
26
+ if (await socketIsLive(socketPath)) {
27
+ throw new Error(
28
+ `Another GTKX MCP server already owns ${socketPath}. ` +
29
+ "Stop the other server (for example, the gtkx MCP server of another active session) and reconnect.",
30
+ );
55
31
  }
56
32
 
57
- getConnections(): AppConnection[] {
58
- return Array.from(this.connections.values());
59
- }
33
+ fs.unlinkSync(socketPath);
34
+ };
60
35
 
61
- getConnection(id: string): AppConnection | undefined {
62
- return this.connections.get(id);
36
+ class SocketServer {
37
+ private server: net.Server | null = null;
38
+ private socketPath: string;
39
+ private registry: ConnectionRegistry;
40
+
41
+ constructor(registry: ConnectionRegistry, socketPath: string = DEFAULT_SOCKET_PATH) {
42
+ this.registry = registry;
43
+ this.socketPath = socketPath;
63
44
  }
64
45
 
65
46
  async start(): Promise<void> {
@@ -67,19 +48,22 @@ export class SocketServer extends EventEmitter<SocketServerEventMap> {
67
48
  return;
68
49
  }
69
50
 
70
- if (fs.existsSync(this.socketPath)) {
71
- fs.unlinkSync(this.socketPath);
72
- }
51
+ await removeStaleSocket(this.socketPath);
73
52
 
74
53
  return new Promise((resolve, reject) => {
75
- this.server = net.createServer((socket) => this.handleConnection(socket));
54
+ this.server = net.createServer((socket) => this.registry.register(socket));
55
+ let isListening = false;
76
56
 
77
57
  this.server.on("error", (error) => {
78
- this.emit("error", error);
79
- reject(error);
58
+ this.registry.dispatchEvent(connectionErrorEvent(error));
59
+
60
+ if (!isListening) {
61
+ reject(error);
62
+ }
80
63
  });
81
64
 
82
65
  this.server.listen(this.socketPath, () => {
66
+ isListening = true;
83
67
  resolve();
84
68
  });
85
69
  });
@@ -90,105 +74,20 @@ export class SocketServer extends EventEmitter<SocketServerEventMap> {
90
74
  return;
91
75
  }
92
76
 
93
- for (const connection of this.connections.values()) {
94
- connection.socket.destroy();
95
- }
96
- this.connections.clear();
77
+ this.registry.dispose("Server stopping");
97
78
 
98
79
  return new Promise((resolve) => {
99
80
  this.server?.close(() => {
100
81
  this.server = null;
82
+
101
83
  if (fs.existsSync(this.socketPath)) {
102
84
  fs.unlinkSync(this.socketPath);
103
85
  }
86
+
104
87
  resolve();
105
88
  });
106
89
  });
107
90
  }
108
-
109
- send(connectionId: string, message: IpcMessage): boolean {
110
- const connection = this.connections.get(connectionId);
111
- if (!connection?.socket.writable) {
112
- return false;
113
- }
114
-
115
- const data = `${JSON.stringify(message)}\n`;
116
- connection.socket.write(data);
117
- return true;
118
- }
119
-
120
- private handleConnection(socket: net.Socket): void {
121
- const connectionId = crypto.randomUUID();
122
- const connection: AppConnection = {
123
- id: connectionId,
124
- socket,
125
- buffer: "",
126
- };
127
-
128
- this.connections.set(connectionId, connection);
129
- this.emit("connection", connection);
130
-
131
- socket.on("data", (data: Buffer) => this.handleData(connection, data));
132
-
133
- socket.on("close", () => {
134
- this.connections.delete(connectionId);
135
- this.emit("disconnection", connection);
136
- });
137
-
138
- socket.on("error", (error) => {
139
- this.emit("error", error);
140
- });
141
- }
142
-
143
- private handleData(connection: AppConnection, data: Buffer): void {
144
- connection.buffer += data.toString();
145
-
146
- let newlineIndex = connection.buffer.indexOf("\n");
147
- while (newlineIndex !== -1) {
148
- const line = connection.buffer.slice(0, newlineIndex);
149
- connection.buffer = connection.buffer.slice(newlineIndex + 1);
150
-
151
- if (line.trim()) {
152
- this.processMessage(connection, line);
153
- }
154
- newlineIndex = connection.buffer.indexOf("\n");
155
- }
156
- }
157
-
158
- private processMessage(connection: AppConnection, line: string): void {
159
- let parsed: unknown;
160
- try {
161
- parsed = JSON.parse(line);
162
- } catch {
163
- const response: IpcResponse = {
164
- id: "unknown",
165
- error: invalidRequestError("Invalid JSON").toIpcError(),
166
- };
167
- this.send(connection.id, response);
168
- return;
169
- }
170
-
171
- const message = parsed as Record<string, unknown>;
172
- const hasMethod = typeof message.method === "string";
173
-
174
- if (hasMethod) {
175
- const requestResult = IpcRequestSchema.safeParse(parsed);
176
- if (requestResult.success) {
177
- this.emit("request", connection, requestResult.data);
178
- return;
179
- }
180
- } else {
181
- const responseResult = IpcResponseSchema.safeParse(parsed);
182
- if (responseResult.success) {
183
- this.emit("response", connection, responseResult.data);
184
- return;
185
- }
186
- }
187
-
188
- const response: IpcResponse = {
189
- id: (message.id as string | undefined) ?? "unknown",
190
- error: invalidRequestError("Invalid message format").toIpcError(),
191
- };
192
- this.send(connection.id, response);
193
- }
194
91
  }
92
+
93
+ export { SocketServer };
package/src/tool.ts ADDED
@@ -0,0 +1,73 @@
1
+ import type { McpServer, ToolCallback } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
3
+ import type { z } from "zod";
4
+ import { ProtocolError } from "./protocol/errors.js";
5
+
6
+ type ToolArgs<Shape extends Record<string, z.ZodType>> = { [K in keyof Shape]: z.output<Shape[K]> };
7
+ type ToolKind = "readOnly" | "action";
8
+
9
+ type Tool<Shape extends Record<string, z.ZodType> = Record<string, z.ZodType>> = {
10
+ name: string;
11
+ title: string;
12
+ kind: ToolKind;
13
+ description: string;
14
+ inputSchema: Shape;
15
+ handler: (args: ToolArgs<Shape>) => Promise<CallToolResult>;
16
+ };
17
+
18
+ const textContent = (text: string): CallToolResult => ({ content: [{ type: "text", text }] });
19
+
20
+ const textError = (text: string): CallToolResult => ({
21
+ content: [{ type: "text", text }],
22
+ isError: true,
23
+ });
24
+
25
+ const imageContent = (data: string, mimeType: string): CallToolResult => ({
26
+ content: [{ type: "image", data, mimeType }],
27
+ });
28
+
29
+ const hasStringHint = (data: unknown): data is { hint: string } =>
30
+ typeof data === "object" && data !== null && "hint" in data && typeof data.hint === "string";
31
+
32
+ const errorToResult = (error: unknown): CallToolResult => {
33
+ if (error instanceof ProtocolError) {
34
+ return textError(hasStringHint(error.data) ? `${error.message}\n${error.data.hint}` : error.message);
35
+ }
36
+
37
+ return textError(error instanceof Error ? error.message : String(error));
38
+ };
39
+
40
+ const runTool = async (
41
+ handler: (args: ToolArgs<Record<string, z.ZodType>>) => Promise<CallToolResult>,
42
+ args: ToolArgs<Record<string, z.ZodType>>,
43
+ ): Promise<CallToolResult> => {
44
+ try {
45
+ return await handler(args);
46
+ } catch (error) {
47
+ return errorToResult(error);
48
+ }
49
+ };
50
+
51
+ const defineTool = <Shape extends Record<string, z.ZodType>>(tool: Tool<Shape>): Tool => tool as Tool;
52
+
53
+ const registerTool = (server: McpServer, tool: Tool): void => {
54
+ const callback = ((args: ToolArgs<Record<string, z.ZodType>>) =>
55
+ runTool(tool.handler, args)) as ToolCallback<Record<string, z.ZodType>>;
56
+
57
+ server.registerTool(
58
+ tool.name,
59
+ {
60
+ description: tool.description,
61
+ inputSchema: tool.inputSchema,
62
+ annotations: {
63
+ title: tool.title,
64
+ readOnlyHint: tool.kind === "readOnly",
65
+ destructiveHint: tool.kind === "action",
66
+ openWorldHint: true,
67
+ },
68
+ },
69
+ callback,
70
+ );
71
+ };
72
+
73
+ export { textContent, textError, imageContent, defineTool, registerTool, type ToolArgs, type Tool };