@modelprofile.com/mcp-crossharness 5.0.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,363 @@
1
+ import * as plugins from './plugins.js';
2
+ import { commitinfo } from './00_commitinfo_data.js';
3
+ import type * as interfaces from './interfaces.js';
4
+ import { ConnectionRegistry } from './classes.connectionregistry.js';
5
+ import { DispatchRegistry } from './classes.dispatchregistry.js';
6
+
7
+ const harnessNameSchema = plugins.z.enum(['claudecode', 'opencode', 'codex']);
8
+
9
+ export class CrossHarnessMcpServer {
10
+ public readonly connections: ConnectionRegistry;
11
+ public readonly dispatches: DispatchRegistry;
12
+ private activeServer: InstanceType<typeof plugins.McpServer> | undefined;
13
+ private stdinEndHandler: (() => void) | undefined;
14
+ private stdinEndSource: NodeJS.ReadableStream | undefined;
15
+ private closePromise: Promise<void> | undefined;
16
+ private resourceShutdownPromise: Promise<void> | undefined;
17
+ private startCalled = false;
18
+
19
+ constructor(connectionsArg = new ConnectionRegistry(), dispatchesArg = new DispatchRegistry()) {
20
+ this.connections = connectionsArg;
21
+ this.dispatches = dispatchesArg;
22
+ }
23
+
24
+ public async start(
25
+ transportArg: plugins.Transport = new plugins.StdioServerTransport(),
26
+ stdinArg: NodeJS.ReadableStream = process.stdin,
27
+ ): Promise<void> {
28
+ if (this.startCalled) throw new Error('Crossharness MCP server instances are one-shot');
29
+ this.startCalled = true;
30
+ const server = new plugins.McpServer({
31
+ name: 'mcp-crossharness',
32
+ version: commitinfo.version,
33
+ });
34
+
35
+ server.registerTool(
36
+ 'connect_harness',
37
+ {
38
+ title: 'Connect to harness server',
39
+ description:
40
+ 'Establish an explicit connection to an allowlisted harness web server. The exact origin must be listed in CROSSHARNESS_ALLOWED_SERVER_URLS. OpenCode uses http(s), Codex uses ws(s), and Claude Code is rejected because it exposes no URL-addressable session server. Returns a connectionId required by every connection-scoped operation; list_connections remains global.',
41
+ inputSchema: {
42
+ harness: harnessNameSchema,
43
+ serverUrl: plugins.z.string().max(2048).url().describe('Allowlisted harness server origin'),
44
+ directory: plugins.z
45
+ .string()
46
+ .max(4096)
47
+ .startsWith('/')
48
+ .describe('Absolute project directory on the harness server'),
49
+ },
50
+ },
51
+ async (args, extra) =>
52
+ this.wrapToolCall(async () => {
53
+ const info = await this.connections.connect(
54
+ args.harness as interfaces.THarnessName,
55
+ args.serverUrl,
56
+ args.directory,
57
+ extra.signal,
58
+ );
59
+ return this.describeConnection(info);
60
+ }),
61
+ );
62
+
63
+ server.registerTool(
64
+ 'disconnect_harness',
65
+ {
66
+ title: 'Disconnect harness server',
67
+ description:
68
+ 'Close and remove an established harness connection. In-flight requests fail; async dispatch records remain inspectable with check_reply.',
69
+ inputSchema: {
70
+ connectionId: plugins.z.string().max(128).describe('Connection id returned by connect_harness'),
71
+ },
72
+ },
73
+ async (args, extra) =>
74
+ this.wrapToolCall(async () =>
75
+ this.describeConnection(await this.connections.disconnect(args.connectionId)),
76
+ ),
77
+ );
78
+
79
+ server.registerTool(
80
+ 'list_connections',
81
+ {
82
+ title: 'List harness connections',
83
+ description: 'List explicit harness web-server connections established in this MCP process.',
84
+ inputSchema: {},
85
+ },
86
+ async () =>
87
+ this.wrapToolCall(async () => {
88
+ const connections = this.connections.list();
89
+ return connections.length > 0
90
+ ? connections.map((connection) => this.describeConnection(connection)).join('\n\n')
91
+ : 'No harness server connections established.';
92
+ }),
93
+ );
94
+
95
+ server.registerTool(
96
+ 'connection_status',
97
+ {
98
+ title: 'Check harness connection',
99
+ description: 'Run the protocol health check for one explicit harness server connection.',
100
+ inputSchema: {
101
+ connectionId: plugins.z.string().max(128).describe('Connection id returned by connect_harness'),
102
+ },
103
+ },
104
+ async (args) =>
105
+ this.wrapToolCall(async () => {
106
+ const status = await this.connections.get(args.connectionId).getStatus();
107
+ return `${this.describeConnection(status)}\nhealthy: ${status.healthy ? 'yes' : 'no'}\ndetail: ${status.detail}`;
108
+ }),
109
+ );
110
+
111
+ server.registerTool(
112
+ 'list_chats',
113
+ {
114
+ title: 'List harness chats',
115
+ description:
116
+ 'List chats from the server and directory bound to an explicit connection. No local session stores are read.',
117
+ inputSchema: {
118
+ connectionId: plugins.z.string().max(128).describe('Connection id returned by connect_harness'),
119
+ limit: plugins.z.number().int().min(1).max(100).optional(),
120
+ },
121
+ },
122
+ async (args) =>
123
+ this.wrapToolCall(async () => {
124
+ const chats = await this.connections.get(args.connectionId).listChats(args.limit ?? 10);
125
+ if (chats.length === 0) return 'No chats found for this connection.';
126
+ return [
127
+ 'harness\tchatId\tupdatedAt\tactivity\ttitle',
128
+ ...chats.map(
129
+ (chat) =>
130
+ `${chat.harness}\t${chat.chatId}\t${chat.updatedAt}\t${chat.isActive ? 'active' : 'idle'}\t${chat.title.replace(/\s+/g, ' ').slice(0, 120)}`,
131
+ ),
132
+ ].join('\n');
133
+ }),
134
+ );
135
+
136
+ server.registerTool(
137
+ 'read_chat',
138
+ {
139
+ title: 'Read harness chat',
140
+ description:
141
+ 'Read a chat through the harness web server bound to an explicit connection.',
142
+ inputSchema: {
143
+ connectionId: plugins.z.string().max(128).describe('Connection id returned by connect_harness'),
144
+ chatId: plugins.z.string().min(1).max(1024),
145
+ limit: plugins.z.number().int().min(1).max(500).optional(),
146
+ maxChars: plugins.z.number().int().min(200).max(50000).optional(),
147
+ },
148
+ },
149
+ async (args) =>
150
+ this.wrapToolCall(async () => {
151
+ const transcript = await this.connections
152
+ .get(args.connectionId)
153
+ .readChat(args.chatId, args.limit ?? 20, args.maxChars ?? 2000);
154
+ const header = [
155
+ `harness: ${transcript.harness}`,
156
+ `chatId: ${transcript.chatId}`,
157
+ `title: ${transcript.title}`,
158
+ `directory: ${transcript.directory}`,
159
+ transcript.totalMessages === undefined
160
+ ? `messages: showing ${transcript.messages.length}; server total unavailable`
161
+ : `messages: showing ${transcript.messages.length} of ${transcript.totalMessages}`,
162
+ ].join('\n');
163
+ const body = transcript.messages
164
+ .map(
165
+ (message) =>
166
+ `-- [${message.role}]${message.timestamp ? ` ${message.timestamp}` : ''}\n${message.text}`,
167
+ )
168
+ .join('\n');
169
+ return `${header}\n\n${body}`;
170
+ }),
171
+ );
172
+
173
+ server.registerTool(
174
+ 'send_message',
175
+ {
176
+ title: 'Send message through harness server',
177
+ description:
178
+ 'Send a message only through the harness web server bound to an explicit connection and wait for the reply. There is no CLI, process, local-store, discovery, or retry fallback.',
179
+ inputSchema: {
180
+ connectionId: plugins.z.string().max(128).describe('Connection id returned by connect_harness'),
181
+ chatId: plugins.z.string().min(1).max(1024),
182
+ message: plugins.z.string().min(1).max(1024 * 1024),
183
+ timeoutSeconds: plugins.z.number().int().min(1).max(3600).optional(),
184
+ },
185
+ },
186
+ async (args, extra) =>
187
+ this.wrapToolCall(async () => {
188
+ const result = await this.connections
189
+ .get(args.connectionId)
190
+ .sendMessage(args.chatId, args.message, args.timeoutSeconds ?? 300, extra.signal);
191
+ return `${result.reply}\n\n[crossharness transport: ${result.via}]`;
192
+ }),
193
+ );
194
+
195
+ server.registerTool(
196
+ 'send_message_async',
197
+ {
198
+ title: 'Send message through harness server asynchronously',
199
+ description:
200
+ 'Start a server-only send and return a dispatchId immediately. Both this connectionId and the dispatchId are required by check_reply.',
201
+ inputSchema: {
202
+ connectionId: plugins.z.string().max(128).describe('Connection id returned by connect_harness'),
203
+ chatId: plugins.z.string().min(1).max(1024),
204
+ message: plugins.z.string().min(1).max(1024 * 1024),
205
+ timeoutSeconds: plugins.z.number().int().min(1).max(3600).optional(),
206
+ },
207
+ },
208
+ async (args) =>
209
+ this.wrapToolCall(async () => {
210
+ const connection = this.connections.get(args.connectionId);
211
+ const record = this.dispatches.track(
212
+ args.connectionId,
213
+ connection.harness,
214
+ args.chatId,
215
+ () => connection.sendMessage(args.chatId, args.message, args.timeoutSeconds ?? 900),
216
+ );
217
+ return [
218
+ `connectionId: ${record.connectionId}`,
219
+ `dispatchId: ${record.dispatchId}`,
220
+ `harness: ${record.harness}`,
221
+ `chatId: ${record.chatId}`,
222
+ `startedAt: ${record.startedAt}`,
223
+ ].join('\n');
224
+ }),
225
+ );
226
+
227
+ server.registerTool(
228
+ 'check_reply',
229
+ {
230
+ title: 'Check async server send',
231
+ description:
232
+ 'Check an asynchronous send. The connectionId must own the dispatch. Records remain inspectable after disconnect.',
233
+ inputSchema: {
234
+ connectionId: plugins.z.string().max(128).describe('Connection id used for send_message_async'),
235
+ dispatchId: plugins.z.string().max(128).describe('Dispatch id returned by send_message_async'),
236
+ waitSeconds: plugins.z.number().int().min(0).max(60).optional(),
237
+ },
238
+ },
239
+ async (args, extra) =>
240
+ this.wrapToolCall(async () => {
241
+ const record = await this.dispatches.waitFor(
242
+ args.connectionId,
243
+ args.dispatchId,
244
+ (args.waitSeconds ?? 0) * 1000,
245
+ extra.signal,
246
+ );
247
+ if (!record) throw new Error('unknown dispatchId for this connectionId');
248
+ const header = [
249
+ `connectionId: ${record.connectionId}`,
250
+ `dispatchId: ${record.dispatchId}`,
251
+ `status: ${record.status}`,
252
+ `harness: ${record.harness}`,
253
+ `chatId: ${record.chatId}`,
254
+ `startedAt: ${record.startedAt}`,
255
+ ...(record.completedAt ? [`completedAt: ${record.completedAt}`] : []),
256
+ ].join('\n');
257
+ if (record.status === 'working') return `${header}\n\nStill working.`;
258
+ if (record.status === 'failed') return `${header}\n\nError: ${record.error}`;
259
+ return `${header}\n\n${record.reply}\n\n[crossharness transport: ${record.via}]`;
260
+ }),
261
+ );
262
+
263
+ this.activeServer = server;
264
+ this.stdinEndHandler = () => this.triggerClose();
265
+ this.stdinEndSource = stdinArg;
266
+ this.stdinEndSource.once('end', this.stdinEndHandler);
267
+ this.stdinEndSource.once('close', this.stdinEndHandler);
268
+ this.stdinEndSource.once('error', this.stdinEndHandler);
269
+ server.server.onclose = () => {
270
+ this.clearTransportReferences();
271
+ void this.ensureResourceShutdown().catch(() => undefined);
272
+ };
273
+ try {
274
+ await server.connect(transportArg);
275
+ } catch (error) {
276
+ this.clearTransportReferences();
277
+ await transportArg.close().catch(() => {});
278
+ await this.ensureResourceShutdown();
279
+ throw error;
280
+ }
281
+ }
282
+
283
+ public async close(): Promise<void> {
284
+ if (this.closePromise) return this.closePromise;
285
+ this.closePromise = (async () => {
286
+ const server = this.activeServer;
287
+ let closeError: unknown;
288
+ try {
289
+ if (server) await server.close();
290
+ } catch (error) {
291
+ closeError = error;
292
+ } finally {
293
+ this.clearTransportReferences();
294
+ await this.ensureResourceShutdown();
295
+ }
296
+ if (closeError) throw closeError;
297
+ })().finally(() => {
298
+ this.closePromise = undefined;
299
+ });
300
+ return this.closePromise;
301
+ }
302
+
303
+ private triggerClose(): void {
304
+ void this.close().catch(() => {});
305
+ }
306
+
307
+ private ensureResourceShutdown(): Promise<void> {
308
+ if (this.resourceShutdownPromise) return this.resourceShutdownPromise;
309
+ let shutdownPromise!: Promise<void>;
310
+ shutdownPromise = this.connections.closeAll().finally(() => {
311
+ this.dispatches.dispose();
312
+ }).catch((errorArg) => {
313
+ if (this.resourceShutdownPromise === shutdownPromise) {
314
+ this.resourceShutdownPromise = undefined;
315
+ }
316
+ throw errorArg;
317
+ });
318
+ this.resourceShutdownPromise = shutdownPromise;
319
+ return shutdownPromise;
320
+ }
321
+
322
+ private clearTransportReferences(): void {
323
+ if (this.stdinEndHandler) {
324
+ this.stdinEndSource?.off('end', this.stdinEndHandler);
325
+ this.stdinEndSource?.off('close', this.stdinEndHandler);
326
+ this.stdinEndSource?.off('error', this.stdinEndHandler);
327
+ }
328
+ this.stdinEndHandler = undefined;
329
+ this.stdinEndSource = undefined;
330
+ this.activeServer = undefined;
331
+ }
332
+
333
+ private describeConnection(infoArg: interfaces.IConnectionInfo): string {
334
+ return [
335
+ `connectionId: ${infoArg.connectionId}`,
336
+ `harness: ${infoArg.harness}`,
337
+ `serverUrl: ${infoArg.serverUrl}`,
338
+ `directory: ${infoArg.directory}`,
339
+ `state: ${infoArg.state}`,
340
+ `connectedAt: ${infoArg.connectedAt}`,
341
+ ...(infoArg.serverVersion ? [`serverVersion: ${infoArg.serverVersion}`] : []),
342
+ ].join('\n');
343
+ }
344
+
345
+ private async wrapToolCall(
346
+ handlerArg: () => Promise<string>,
347
+ ): Promise<{ content: Array<{ type: 'text'; text: string }>; isError?: boolean }> {
348
+ try {
349
+ const text = await handlerArg();
350
+ return { content: [{ type: 'text', text: text.slice(0, 100000) }] };
351
+ } catch (error) {
352
+ return {
353
+ content: [
354
+ {
355
+ type: 'text',
356
+ text: `Error: ${error instanceof Error ? error.message : String(error)}`.slice(0, 100000),
357
+ },
358
+ ],
359
+ isError: true,
360
+ };
361
+ }
362
+ }
363
+ }
package/ts/helpers.ts ADDED
@@ -0,0 +1,20 @@
1
+ export const truncateText = (textArg: string, maxCharsArg: number): string => {
2
+ if (textArg.length <= maxCharsArg) {
3
+ return textArg;
4
+ }
5
+ return `${textArg.slice(0, maxCharsArg)}\n[truncated ${textArg.length - maxCharsArg} chars]`;
6
+ };
7
+
8
+ export const parseJson = (valueArg: string): unknown => {
9
+ try {
10
+ return JSON.parse(valueArg);
11
+ } catch {
12
+ return undefined;
13
+ }
14
+ };
15
+
16
+ export const isRecord = (valueArg: unknown): valueArg is Record<string, unknown> =>
17
+ Boolean(valueArg) && typeof valueArg === 'object' && !Array.isArray(valueArg);
18
+
19
+ export const errorMessage = (errorArg: unknown): string =>
20
+ errorArg instanceof Error ? errorArg.message : String(errorArg);
package/ts/index.ts ADDED
@@ -0,0 +1,10 @@
1
+ export * from './interfaces.js';
2
+ export * from './classes.connectionregistry.js';
3
+ export * from './classes.dispatchregistry.js';
4
+ export * from './classes.mcpserver.js';
5
+
6
+ import { CrossHarnessMcpServer } from './classes.mcpserver.js';
7
+
8
+ export const runCli = async (): Promise<void> => {
9
+ await new CrossHarnessMcpServer().start();
10
+ };
@@ -0,0 +1,71 @@
1
+ export type THarnessName = 'claudecode' | 'opencode' | 'codex';
2
+
3
+ export type TConnectionState = 'connecting' | 'connected' | 'closing' | 'closed';
4
+
5
+ export interface IConnectionInfo {
6
+ connectionId: string;
7
+ harness: THarnessName;
8
+ serverUrl: string;
9
+ directory: string;
10
+ state: TConnectionState;
11
+ connectedAt: string;
12
+ serverVersion?: string;
13
+ }
14
+
15
+ export interface IConnectionStatus extends IConnectionInfo {
16
+ healthy: boolean;
17
+ detail: string;
18
+ }
19
+
20
+ export interface IChatSummary {
21
+ harness: THarnessName;
22
+ chatId: string;
23
+ title: string;
24
+ directory: string;
25
+ updatedAt: string;
26
+ isActive?: boolean;
27
+ meta?: Record<string, string>;
28
+ }
29
+
30
+ export interface IChatMessage {
31
+ role: string;
32
+ text: string;
33
+ timestamp?: string;
34
+ }
35
+
36
+ export interface IChatTranscript {
37
+ harness: THarnessName;
38
+ chatId: string;
39
+ title: string;
40
+ directory: string;
41
+ totalMessages?: number;
42
+ messages: IChatMessage[];
43
+ }
44
+
45
+ export interface ISendResult {
46
+ harness: THarnessName;
47
+ chatId: string;
48
+ reply: string;
49
+ via: string;
50
+ }
51
+
52
+ export interface IHarnessConnection {
53
+ readonly connectionId: string;
54
+ readonly harness: THarnessName;
55
+ readonly serverUrl: string;
56
+ readonly directory: string;
57
+ readonly state: TConnectionState;
58
+
59
+ connect(): Promise<void>;
60
+ getInfo(): IConnectionInfo;
61
+ getStatus(): Promise<IConnectionStatus>;
62
+ listChats(limitArg: number): Promise<IChatSummary[]>;
63
+ readChat(chatIdArg: string, limitArg: number, maxCharsArg: number): Promise<IChatTranscript>;
64
+ sendMessage(
65
+ chatIdArg: string,
66
+ messageArg: string,
67
+ timeoutSecondsArg: number,
68
+ signalArg?: AbortSignal,
69
+ ): Promise<ISendResult>;
70
+ close(reasonArg?: string): Promise<void>;
71
+ }
package/ts/plugins.ts ADDED
@@ -0,0 +1,30 @@
1
+ // Node native modules
2
+ import * as crypto from 'node:crypto';
3
+ import * as http from 'node:http';
4
+ import * as stream from 'node:stream';
5
+ import type { AddressInfo } from 'node:net';
6
+
7
+ export { crypto, http, stream };
8
+ export type { AddressInfo };
9
+
10
+ // Third-party modules
11
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
12
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
13
+ import { Client as McpClient } from '@modelcontextprotocol/sdk/client/index.js';
14
+ import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
15
+ import type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js';
16
+ import { WebSocket as WsWebSocket, WebSocketServer } from 'ws';
17
+ import type { RawData } from 'ws';
18
+ import { z } from 'zod';
19
+
20
+ export {
21
+ InMemoryTransport,
22
+ McpClient,
23
+ McpServer,
24
+ StdioServerTransport,
25
+ WebSocketServer,
26
+ WsWebSocket,
27
+ z,
28
+ };
29
+ export type { RawData };
30
+ export type { Transport };