@truefoundry/trueforge-core 0.2.0-rc.4 → 0.2.0-rc.5
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/core/mcp/RemoteMCP.d.ts.map +1 -1
- package/dist/core/mcp/RemoteMCP.js +8 -1
- package/dist/core/mcp/RemoteMCP.js.map +1 -1
- package/dist/core/mcp/RemoteMCP.mjs +8 -1
- package/dist/core/mcp/RemoteMCP.mjs.map +1 -1
- package/dist/core/mcp/remoteMcpClient.d.ts.map +1 -1
- package/dist/core/mcp/remoteMcpClient.js +14 -3
- package/dist/core/mcp/remoteMcpClient.js.map +1 -1
- package/dist/core/mcp/remoteMcpClient.mjs +14 -3
- package/dist/core/mcp/remoteMcpClient.mjs.map +1 -1
- package/dist/request-reply/client.d.ts +2 -2
- package/dist/request-reply/client.d.ts.map +1 -1
- package/dist/request-reply/client.js +3 -0
- package/dist/request-reply/client.js.map +1 -1
- package/dist/request-reply/client.mjs +3 -0
- package/dist/request-reply/client.mjs.map +1 -1
- package/package.json +2 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"RemoteMCP.d.ts","sourceRoot":"","sources":["../../../src/core/mcp/RemoteMCP.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,oCAAoC,CAAC;AAC1E,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AAGtC,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AAC5D,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;
|
|
1
|
+
{"version":3,"file":"RemoteMCP.d.ts","sourceRoot":"","sources":["../../../src/core/mcp/RemoteMCP.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,oCAAoC,CAAC;AAC1E,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AAGtC,O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ports);
|
|
26
26
|
var import_errors = require("../errors.js");
|
|
27
27
|
var import_NoopAgentTracing = require("../tracing/NoopAgentTracing.js");
|
|
28
|
+
var import_errorLogFields = require("../util/errorLogFields.js");
|
|
28
29
|
var import_IMCPServer = require("./IMCPServer.js");
|
|
29
30
|
var import_pagination = require("./pagination.js");
|
|
30
31
|
var import_remoteMcpClient = require("./remoteMcpClient.js");
|
|
@@ -210,7 +211,13 @@ var RemoteMCP = class {
|
|
|
210
211
|
this.isConnected = false;
|
|
211
212
|
},
|
|
212
213
|
onError: (error) => {
|
|
213
|
-
|
|
214
|
+
const fields = (0, import_errorLogFields.extractErrorLogFields)(error);
|
|
215
|
+
const msg = `Error on remote MCP transport ${this.name}`;
|
|
216
|
+
if (fields.error.includes("Body Timeout")) {
|
|
217
|
+
this.logger.warn(msg, fields);
|
|
218
|
+
} else {
|
|
219
|
+
this.logger.error(msg, fields);
|
|
220
|
+
}
|
|
214
221
|
}
|
|
215
222
|
});
|
|
216
223
|
span.setOutput(JSON.stringify({ transport: conn.transportType, stateful: conn.sessionId !== null }));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/core/mcp/RemoteMCP.ts"],"sourcesContent":["import type { CallToolRequest } from '@modelcontextprotocol/sdk/types.js';\nimport type { Logger } from 'winston';\nimport { McpConnectionError } from '../errors';\nimport type { MCPServerInitInfo } from '../events/schema';\nimport type { InternalToolCallInfo } from '../llm/LLMTypes';\nimport type { AgentTracing } from '../tracing/AgentTracing';\nimport { NOOP_AGENT_TRACING } from '../tracing/NoopAgentTracing';\nimport {\n type AgentToolSchema,\n type AuthRequiredResponse,\n type CallToolResolvedResponse,\n type ListToolsResolvedResponse,\n type MCPAuthRequired,\n type ToolSource,\n} from './IMCPServer';\nimport { paginateWithCursorGuard } from './pagination';\nimport {\n connectRemoteMcp,\n isSessionExpiredError,\n type RemoteMcpConnection,\n type RemoteMcpTransportType,\n} from './remoteMcpClient';\n\n/** Redacted url for trace spans: scheme + host + path only, so userinfo/query secrets never leak. */\nfunction redactUrlForTrace(url: string): string {\n try {\n const u = new URL(url);\n return `${u.protocol}//${u.host}${u.pathname}`;\n } catch {\n return '';\n }\n}\n\n/** What a headers resolver returns: the headers to send, or a signal that auth is required. */\nexport type ResolveHeadersResult = { headers: Record<string, string> } | { authRequired: MCPAuthRequired };\n\n/** Static headers, or a resolver (invoked at connect) returning headers or signalling auth-required. */\nexport type RemoteMcpHeaders = Record<string, string> | (() => Promise<ResolveHeadersResult>);\n\ntype ExecuteResult<T> = { result: T; wasInitialized: MCPServerInitInfo | undefined } | AuthRequiredResponse;\n\n/**\n * Connection/session half of a remote MCP server: owns the transport (connects itself from `url` +\n * `headers`), session id, raw tool cache, connect single-flight and session-expiry retry. Policy-free\n * — a per-agent {@link ToolSet} layers policy.\n */\nexport class RemoteMCP implements ToolSource {\n readonly name: string;\n readonly id: string;\n readonly description?: string | undefined;\n\n private readonly url: string;\n private readonly headers: RemoteMcpHeaders;\n private readonly signal: AbortSignal;\n private readonly logger: Logger;\n private readonly tracing: AgentTracing;\n private readonly requestTimeoutMs: number;\n private readonly connectTimeoutMs: number;\n // Redacted display url for trace spans (derived from url; unused when tracing is a no-op).\n private readonly traceUrl: string;\n\n private _connection?: RemoteMcpConnection | undefined;\n private isConnected = false;\n private connectPromise: Promise<MCPServerInitInfo | undefined> | undefined;\n // undefined = never connected, string = stateful session id, null = stateless/SSE.\n private sessionId: string | null | undefined;\n private resolvedTransportType?: RemoteMcpTransportType | undefined;\n private cachedTools?: AgentToolSchema[] | undefined;\n\n constructor(params: {\n name: string;\n id: string;\n description?: string | undefined;\n url: string;\n headers: RemoteMcpHeaders;\n logger: Logger;\n tracing?: AgentTracing | undefined;\n sessionId?: string | undefined;\n transportType?: RemoteMcpTransportType | undefined;\n requestTimeoutMs: number;\n connectTimeoutMs: number;\n signal: AbortSignal;\n }) {\n this.name = params.name;\n this.id = params.id;\n this.description = params.description;\n this.url = params.url;\n this.headers = params.headers;\n this.signal = params.signal;\n this.sessionId = params.sessionId;\n this.resolvedTransportType = params.transportType;\n this.requestTimeoutMs = params.requestTimeoutMs;\n this.connectTimeoutMs = params.connectTimeoutMs;\n this.logger = params.logger;\n this.tracing = params.tracing ?? NOOP_AGENT_TRACING;\n this.traceUrl = redactUrlForTrace(params.url);\n }\n\n getSessionId(): string | undefined {\n return this.sessionId ?? undefined;\n }\n\n private get connection(): RemoteMcpConnection {\n if (!this._connection) {\n throw new Error(`Remote MCP '${this.name}' not connected - connectIfNeeded() must run first`);\n }\n return this._connection;\n }\n\n private async resetConnection(): Promise<void> {\n this.isConnected = false;\n this.sessionId = undefined;\n this.cachedTools = undefined;\n this.connectPromise = undefined;\n await this.closeAndClearConnection();\n }\n\n private async closeAndClearConnection(): Promise<void> {\n await this._connection?.close().catch(() => {\n /* no-op */\n });\n this._connection = undefined;\n }\n\n private async resolveHeaders(): Promise<ResolveHeadersResult> {\n if (typeof this.headers !== 'function') {\n return { headers: this.headers };\n }\n return await this.headers();\n }\n\n private async executeWithSessionRetry<T>(operation: () => Promise<T>): Promise<ExecuteResult<T>> {\n // Auth is re-checked on every operation, not only on the first connect: a registered server's OAuth\n // can be revoked or expire mid-request, and callers must get authRequired rather than a generic\n // upstream failure. When already connected the resolved headers are unused (connect is skipped).\n const headersResult = await this.resolveHeaders();\n if ('authRequired' in headersResult) {\n return { authRequired: headersResult.authRequired };\n }\n return this.connectAndRun(headersResult.headers, operation, true);\n }\n\n private async connectAndRun<T>(\n headers: Record<string, string>,\n operation: () => Promise<T>,\n canRetry: boolean,\n ): Promise<ExecuteResult<T>> {\n try {\n const initInfo = await this.connectIfNeeded(headers);\n return { result: await operation(), wasInitialized: initInfo };\n } catch (error) {\n if (canRetry && isSessionExpiredError(error)) {\n this.logger.info(`Session expired for remote MCP ${this.name}, reinitializing...`);\n await this.resetConnection();\n return this.connectAndRun(headers, operation, false);\n }\n throw error;\n }\n }\n\n private async loadTools(): Promise<{ tools: AgentToolSchema[] }> {\n return this.tracing.withRemoteMcpToolSpan(\n { method: 'tools/list', serverName: this.name, serverId: this.id, serverUrl: this.traceUrl, enabled: true },\n async span => {\n const tools = await paginateWithCursorGuard(\n async cursor => {\n const page = await this.connection.listTools(cursor);\n return { items: page.tools, nextCursor: page.nextCursor };\n },\n this.name,\n this.logger,\n );\n this.cachedTools = tools.map(t => ({ ...t, preload: true }));\n span.setNumberOfTools(this.cachedTools.length);\n return { tools: this.cachedTools };\n },\n );\n }\n\n /** Unfiltered tool list (no policy). The per-agent wrapper applies selectors on top. */\n async listTools(): Promise<ListToolsResolvedResponse | AuthRequiredResponse> {\n if (this.cachedTools) {\n return { result: { tools: this.cachedTools }, wasInitialized: undefined };\n }\n const response = await this.executeWithSessionRetry(() => this.loadTools());\n if ('authRequired' in response) {\n return response;\n }\n return { result: { tools: response.result.tools }, wasInitialized: response.wasInitialized };\n }\n\n async callTool(params: CallToolRequest['params']): Promise<CallToolResolvedResponse | AuthRequiredResponse> {\n const response = await this.executeWithSessionRetry(() =>\n this.tracing.withRemoteMcpToolSpan(\n {\n method: 'tools/call',\n serverName: this.name,\n serverId: this.id,\n serverUrl: this.traceUrl,\n toolName: params.name,\n input: JSON.stringify(params.arguments),\n enabled: true,\n },\n async span => {\n const result = await this.connection.callTool(params);\n span.setOutput(JSON.stringify(result));\n return result;\n },\n ),\n );\n if ('authRequired' in response) {\n return response;\n }\n return { result: response.result, wasInitialized: response.wasInitialized };\n }\n\n toolCallInfo(params: CallToolRequest['params'], _resolveUnderlyingTool?: boolean): Promise<InternalToolCallInfo> {\n void _resolveUnderlyingTool;\n return Promise.resolve({\n type: 'mcp',\n original_tool_name: params.name,\n mcp_server_id: this.id,\n mcp_server_name: this.name,\n is_approval_required: false,\n });\n }\n\n private async connectIfNeeded(headers: Record<string, string>): Promise<MCPServerInitInfo | undefined> {\n if (this.isConnected) {\n return undefined;\n }\n if (this.connectPromise) {\n // Wait for the in-flight connect, but only its originator emits the init metadata.\n await this.connectPromise;\n return undefined;\n }\n\n const existingSessionId = this.sessionId;\n this.connectPromise = (async (): Promise<MCPServerInitInfo | undefined> => {\n let connection: RemoteMcpConnection;\n try {\n await this.closeAndClearConnection();\n connection = await this.tracing.withRemoteMcpToolSpan(\n { method: 'initialize', serverName: this.name, serverId: this.id, serverUrl: this.traceUrl, enabled: true },\n async span => {\n const conn = await connectRemoteMcp({\n url: this.url,\n headers,\n sessionId: this.sessionId ?? undefined,\n // Hint from a prior connect\n knownTransportType: this.resolvedTransportType,\n requestTimeoutMs: this.requestTimeoutMs,\n connectTimeoutMs: this.connectTimeoutMs,\n signal: this.signal,\n onClose: () => {\n this.isConnected = false;\n },\n onError: error => {\n this.logger.error(`Error on remote MCP transport ${this.name}`, { error });\n },\n });\n span.setOutput(JSON.stringify({ transport: conn.transportType, stateful: conn.sessionId !== null }));\n return conn;\n },\n );\n } catch (error) {\n await this.closeAndClearConnection();\n throw this.toConnectError(error);\n }\n this._connection = connection;\n this.resolvedTransportType = connection.transportType;\n this.isConnected = true;\n this.sessionId = connection.sessionId;\n if (existingSessionId === this.sessionId) {\n return undefined;\n }\n return {\n name: this.name,\n id: this.id,\n session_id: this.sessionId ?? undefined,\n transport_type: this.resolvedTransportType,\n };\n })().finally(() => {\n this.connectPromise = undefined;\n });\n return this.connectPromise;\n }\n\n private toConnectError(error: unknown): McpConnectionError {\n const statusCode = error instanceof McpConnectionError ? error.statusCode : 502;\n const message = error instanceof Error ? error.message : String(error);\n return new McpConnectionError(`Failed to connect to remote MCP server '${this.name}': ${message}`, statusCode, {\n cause: error,\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,oBAAmC;AAInC,8BAAmC;AACnC,wBAOO;AACP,wBAAwC;AACxC,6BAKO;AAGP,SAAS,kBAAkB,KAAqB;AAC9C,MAAI;AACF,UAAM,IAAI,IAAI,IAAI,GAAG;AACrB,WAAO,GAAG,EAAE,QAAQ,KAAK,EAAE,IAAI,GAAG,EAAE,QAAQ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AC;AACD,WAAO,KAAK;AAAA,EACd;AAAA,EAEQ,eAAe,OAAoC;AACzD,UAAM,aAAa,iBAAiB,mCAAqB,MAAM,aAAa;AAC5E,UAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACrE,WAAO,IAAI,iCAAmB,2CAA2C,KAAK,IAAI,MAAM,OAAO,IAAI,YAAY;AAAA,MAC7G,OAAO;AAAA,IACT,CAAC;AAAA,EACH;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../../src/core/mcp/RemoteMCP.ts"],"sourcesContent":["import type { CallToolRequest } from '@modelcontextprotocol/sdk/types.js';\nimport type { Logger } from 'winston';\nimport { McpConnectionError } from '../errors';\nimport type { MCPServerInitInfo } from '../events/schema';\nimport type { InternalToolCallInfo } from '../llm/LLMTypes';\nimport type { AgentTracing } from '../tracing/AgentTracing';\nimport { NOOP_AGENT_TRACING } from '../tracing/NoopAgentTracing';\nimport { extractErrorLogFields } from '../util/errorLogFields';\nimport {\n type AgentToolSchema,\n type AuthRequiredResponse,\n type CallToolResolvedResponse,\n type ListToolsResolvedResponse,\n type MCPAuthRequired,\n type ToolSource,\n} from './IMCPServer';\nimport { paginateWithCursorGuard } from './pagination';\nimport {\n connectRemoteMcp,\n isSessionExpiredError,\n type RemoteMcpConnection,\n type RemoteMcpTransportType,\n} from './remoteMcpClient';\n\n/** Redacted url for trace spans: scheme + host + path only, so userinfo/query secrets never leak. */\nfunction redactUrlForTrace(url: string): string {\n try {\n const u = new URL(url);\n return `${u.protocol}//${u.host}${u.pathname}`;\n } catch {\n return '';\n }\n}\n\n/** What a headers resolver returns: the headers to send, or a signal that auth is required. */\nexport type ResolveHeadersResult = { headers: Record<string, string> } | { authRequired: MCPAuthRequired };\n\n/** Static headers, or a resolver (invoked at connect) returning headers or signalling auth-required. */\nexport type RemoteMcpHeaders = Record<string, string> | (() => Promise<ResolveHeadersResult>);\n\ntype ExecuteResult<T> = { result: T; wasInitialized: MCPServerInitInfo | undefined } | AuthRequiredResponse;\n\n/**\n * Connection/session half of a remote MCP server: owns the transport (connects itself from `url` +\n * `headers`), session id, raw tool cache, connect single-flight and session-expiry retry. Policy-free\n * — a per-agent {@link ToolSet} layers policy.\n */\nexport class RemoteMCP implements ToolSource {\n readonly name: string;\n readonly id: string;\n readonly description?: string | undefined;\n\n private readonly url: string;\n private readonly headers: RemoteMcpHeaders;\n private readonly signal: AbortSignal;\n private readonly logger: Logger;\n private readonly tracing: AgentTracing;\n private readonly requestTimeoutMs: number;\n private readonly connectTimeoutMs: number;\n // Redacted display url for trace spans (derived from url; unused when tracing is a no-op).\n private readonly traceUrl: string;\n\n private _connection?: RemoteMcpConnection | undefined;\n private isConnected = false;\n private connectPromise: Promise<MCPServerInitInfo | undefined> | undefined;\n // undefined = never connected, string = stateful session id, null = stateless/SSE.\n private sessionId: string | null | undefined;\n private resolvedTransportType?: RemoteMcpTransportType | undefined;\n private cachedTools?: AgentToolSchema[] | undefined;\n\n constructor(params: {\n name: string;\n id: string;\n description?: string | undefined;\n url: string;\n headers: RemoteMcpHeaders;\n logger: Logger;\n tracing?: AgentTracing | undefined;\n sessionId?: string | undefined;\n transportType?: RemoteMcpTransportType | undefined;\n requestTimeoutMs: number;\n connectTimeoutMs: number;\n signal: AbortSignal;\n }) {\n this.name = params.name;\n this.id = params.id;\n this.description = params.description;\n this.url = params.url;\n this.headers = params.headers;\n this.signal = params.signal;\n this.sessionId = params.sessionId;\n this.resolvedTransportType = params.transportType;\n this.requestTimeoutMs = params.requestTimeoutMs;\n this.connectTimeoutMs = params.connectTimeoutMs;\n this.logger = params.logger;\n this.tracing = params.tracing ?? NOOP_AGENT_TRACING;\n this.traceUrl = redactUrlForTrace(params.url);\n }\n\n getSessionId(): string | undefined {\n return this.sessionId ?? undefined;\n }\n\n private get connection(): RemoteMcpConnection {\n if (!this._connection) {\n throw new Error(`Remote MCP '${this.name}' not connected - connectIfNeeded() must run first`);\n }\n return this._connection;\n }\n\n private async resetConnection(): Promise<void> {\n this.isConnected = false;\n this.sessionId = undefined;\n this.cachedTools = undefined;\n this.connectPromise = undefined;\n await this.closeAndClearConnection();\n }\n\n private async closeAndClearConnection(): Promise<void> {\n await this._connection?.close().catch(() => {\n /* no-op */\n });\n this._connection = undefined;\n }\n\n private async resolveHeaders(): Promise<ResolveHeadersResult> {\n if (typeof this.headers !== 'function') {\n return { headers: this.headers };\n }\n return await this.headers();\n }\n\n private async executeWithSessionRetry<T>(operation: () => Promise<T>): Promise<ExecuteResult<T>> {\n // Auth is re-checked on every operation, not only on the first connect: a registered server's OAuth\n // can be revoked or expire mid-request, and callers must get authRequired rather than a generic\n // upstream failure. When already connected the resolved headers are unused (connect is skipped).\n const headersResult = await this.resolveHeaders();\n if ('authRequired' in headersResult) {\n return { authRequired: headersResult.authRequired };\n }\n return this.connectAndRun(headersResult.headers, operation, true);\n }\n\n private async connectAndRun<T>(\n headers: Record<string, string>,\n operation: () => Promise<T>,\n canRetry: boolean,\n ): Promise<ExecuteResult<T>> {\n try {\n const initInfo = await this.connectIfNeeded(headers);\n return { result: await operation(), wasInitialized: initInfo };\n } catch (error) {\n if (canRetry && isSessionExpiredError(error)) {\n this.logger.info(`Session expired for remote MCP ${this.name}, reinitializing...`);\n await this.resetConnection();\n return this.connectAndRun(headers, operation, false);\n }\n throw error;\n }\n }\n\n private async loadTools(): Promise<{ tools: AgentToolSchema[] }> {\n return this.tracing.withRemoteMcpToolSpan(\n { method: 'tools/list', serverName: this.name, serverId: this.id, serverUrl: this.traceUrl, enabled: true },\n async span => {\n const tools = await paginateWithCursorGuard(\n async cursor => {\n const page = await this.connection.listTools(cursor);\n return { items: page.tools, nextCursor: page.nextCursor };\n },\n this.name,\n this.logger,\n );\n this.cachedTools = tools.map(t => ({ ...t, preload: true }));\n span.setNumberOfTools(this.cachedTools.length);\n return { tools: this.cachedTools };\n },\n );\n }\n\n /** Unfiltered tool list (no policy). The per-agent wrapper applies selectors on top. */\n async listTools(): Promise<ListToolsResolvedResponse | AuthRequiredResponse> {\n if (this.cachedTools) {\n return { result: { tools: this.cachedTools }, wasInitialized: undefined };\n }\n const response = await this.executeWithSessionRetry(() => this.loadTools());\n if ('authRequired' in response) {\n return response;\n }\n return { result: { tools: response.result.tools }, wasInitialized: response.wasInitialized };\n }\n\n async callTool(params: CallToolRequest['params']): Promise<CallToolResolvedResponse | AuthRequiredResponse> {\n const response = await this.executeWithSessionRetry(() =>\n this.tracing.withRemoteMcpToolSpan(\n {\n method: 'tools/call',\n serverName: this.name,\n serverId: this.id,\n serverUrl: this.traceUrl,\n toolName: params.name,\n input: JSON.stringify(params.arguments),\n enabled: true,\n },\n async span => {\n const result = await this.connection.callTool(params);\n span.setOutput(JSON.stringify(result));\n return result;\n },\n ),\n );\n if ('authRequired' in response) {\n return response;\n }\n return { result: response.result, wasInitialized: response.wasInitialized };\n }\n\n toolCallInfo(params: CallToolRequest['params'], _resolveUnderlyingTool?: boolean): Promise<InternalToolCallInfo> {\n void _resolveUnderlyingTool;\n return Promise.resolve({\n type: 'mcp',\n original_tool_name: params.name,\n mcp_server_id: this.id,\n mcp_server_name: this.name,\n is_approval_required: false,\n });\n }\n\n private async connectIfNeeded(headers: Record<string, string>): Promise<MCPServerInitInfo | undefined> {\n if (this.isConnected) {\n return undefined;\n }\n if (this.connectPromise) {\n // Wait for the in-flight connect, but only its originator emits the init metadata.\n await this.connectPromise;\n return undefined;\n }\n\n const existingSessionId = this.sessionId;\n this.connectPromise = (async (): Promise<MCPServerInitInfo | undefined> => {\n let connection: RemoteMcpConnection;\n try {\n await this.closeAndClearConnection();\n connection = await this.tracing.withRemoteMcpToolSpan(\n { method: 'initialize', serverName: this.name, serverId: this.id, serverUrl: this.traceUrl, enabled: true },\n async span => {\n const conn = await connectRemoteMcp({\n url: this.url,\n headers,\n sessionId: this.sessionId ?? undefined,\n // Hint from a prior connect\n knownTransportType: this.resolvedTransportType,\n requestTimeoutMs: this.requestTimeoutMs,\n connectTimeoutMs: this.connectTimeoutMs,\n signal: this.signal,\n onClose: () => {\n this.isConnected = false;\n },\n onError: error => {\n const fields = extractErrorLogFields(error);\n const msg = `Error on remote MCP transport ${this.name}`;\n if (fields.error.includes('Body Timeout')) {\n this.logger.warn(msg, fields);\n } else {\n this.logger.error(msg, fields);\n }\n },\n });\n span.setOutput(JSON.stringify({ transport: conn.transportType, stateful: conn.sessionId !== null }));\n return conn;\n },\n );\n } catch (error) {\n await this.closeAndClearConnection();\n throw this.toConnectError(error);\n }\n this._connection = connection;\n this.resolvedTransportType = connection.transportType;\n this.isConnected = true;\n this.sessionId = connection.sessionId;\n if (existingSessionId === this.sessionId) {\n return undefined;\n }\n return {\n name: this.name,\n id: this.id,\n session_id: this.sessionId ?? undefined,\n transport_type: this.resolvedTransportType,\n };\n })().finally(() => {\n this.connectPromise = undefined;\n });\n return this.connectPromise;\n }\n\n private toConnectError(error: unknown): McpConnectionError {\n const statusCode = error instanceof McpConnectionError ? error.statusCode : 502;\n const message = error instanceof Error ? error.message : String(error);\n return new McpConnectionError(`Failed to connect to remote MCP server '${this.name}': ${message}`, statusCode, {\n cause: error,\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,oBAAmC;AAInC,8BAAmC;AACnC,4BAAsC;AACtC,wBAOO;AACP,wBAAwC;AACxC,6BAKO;AAGP,SAAS,kBAAkB,KAAqB;AAC9C,MAAI;AACF,UAAM,IAAI,IAAI,IAAI,GAAG;AACrB,WAAO,GAAG,EAAE,QAAQ,KAAK,EAAE,IAAI,GAAG,EAAE,QAAQ;AAAA,EAC9C,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAeO,IAAM,YAAN,MAAsC;AAAA,EAClC;AAAA,EACA;AAAA,EACA;AAAA,EAEQ;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EAET;AAAA,EACA,cAAc;AAAA,EACd;AAAA;AAAA,EAEA;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AC5E,UAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACrE,WAAO,IAAI,iCAAmB,2CAA2C,KAAK,IAAI,MAAM,OAAO,IAAI,YAAY;AAAA,MAC7G,OAAO;AAAA,IACT,CAAC;AAAA,EACH;AACF;","names":[]}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// src/core/mcp/RemoteMCP.ts
|
|
2
2
|
import { McpConnectionError } from "../errors.mjs";
|
|
3
3
|
import { NOOP_AGENT_TRACING } from "../tracing/NoopAgentTracing.mjs";
|
|
4
|
+
import { extractErrorLogFields } from "../util/errorLogFields.mjs";
|
|
4
5
|
import "./IMCPServer.mjs";
|
|
5
6
|
import { paginateWithCursorGuard } from "./pagination.mjs";
|
|
6
7
|
import {
|
|
@@ -189,7 +190,13 @@ var RemoteMCP = class {
|
|
|
189
190
|
this.isConnected = false;
|
|
190
191
|
},
|
|
191
192
|
onError: (error) => {
|
|
192
|
-
|
|
193
|
+
const fields = extractErrorLogFields(error);
|
|
194
|
+
const msg = `Error on remote MCP transport ${this.name}`;
|
|
195
|
+
if (fields.error.includes("Body Timeout")) {
|
|
196
|
+
this.logger.warn(msg, fields);
|
|
197
|
+
} else {
|
|
198
|
+
this.logger.error(msg, fields);
|
|
199
|
+
}
|
|
193
200
|
}
|
|
194
201
|
});
|
|
195
202
|
span.setOutput(JSON.stringify({ transport: conn.transportType, stateful: conn.sessionId !== null }));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/core/mcp/RemoteMCP.ts"],"sourcesContent":["import type { CallToolRequest } from '@modelcontextprotocol/sdk/types.js';\nimport type { Logger } from 'winston';\nimport { McpConnectionError } from '../errors';\nimport type { MCPServerInitInfo } from '../events/schema';\nimport type { InternalToolCallInfo } from '../llm/LLMTypes';\nimport type { AgentTracing } from '../tracing/AgentTracing';\nimport { NOOP_AGENT_TRACING } from '../tracing/NoopAgentTracing';\nimport {\n type AgentToolSchema,\n type AuthRequiredResponse,\n type CallToolResolvedResponse,\n type ListToolsResolvedResponse,\n type MCPAuthRequired,\n type ToolSource,\n} from './IMCPServer';\nimport { paginateWithCursorGuard } from './pagination';\nimport {\n connectRemoteMcp,\n isSessionExpiredError,\n type RemoteMcpConnection,\n type RemoteMcpTransportType,\n} from './remoteMcpClient';\n\n/** Redacted url for trace spans: scheme + host + path only, so userinfo/query secrets never leak. */\nfunction redactUrlForTrace(url: string): string {\n try {\n const u = new URL(url);\n return `${u.protocol}//${u.host}${u.pathname}`;\n } catch {\n return '';\n }\n}\n\n/** What a headers resolver returns: the headers to send, or a signal that auth is required. */\nexport type ResolveHeadersResult = { headers: Record<string, string> } | { authRequired: MCPAuthRequired };\n\n/** Static headers, or a resolver (invoked at connect) returning headers or signalling auth-required. */\nexport type RemoteMcpHeaders = Record<string, string> | (() => Promise<ResolveHeadersResult>);\n\ntype ExecuteResult<T> = { result: T; wasInitialized: MCPServerInitInfo | undefined } | AuthRequiredResponse;\n\n/**\n * Connection/session half of a remote MCP server: owns the transport (connects itself from `url` +\n * `headers`), session id, raw tool cache, connect single-flight and session-expiry retry. Policy-free\n * — a per-agent {@link ToolSet} layers policy.\n */\nexport class RemoteMCP implements ToolSource {\n readonly name: string;\n readonly id: string;\n readonly description?: string | undefined;\n\n private readonly url: string;\n private readonly headers: RemoteMcpHeaders;\n private readonly signal: AbortSignal;\n private readonly logger: Logger;\n private readonly tracing: AgentTracing;\n private readonly requestTimeoutMs: number;\n private readonly connectTimeoutMs: number;\n // Redacted display url for trace spans (derived from url; unused when tracing is a no-op).\n private readonly traceUrl: string;\n\n private _connection?: RemoteMcpConnection | undefined;\n private isConnected = false;\n private connectPromise: Promise<MCPServerInitInfo | undefined> | undefined;\n // undefined = never connected, string = stateful session id, null = stateless/SSE.\n private sessionId: string | null | undefined;\n private resolvedTransportType?: RemoteMcpTransportType | undefined;\n private cachedTools?: AgentToolSchema[] | undefined;\n\n constructor(params: {\n name: string;\n id: string;\n description?: string | undefined;\n url: string;\n headers: RemoteMcpHeaders;\n logger: Logger;\n tracing?: AgentTracing | undefined;\n sessionId?: string | undefined;\n transportType?: RemoteMcpTransportType | undefined;\n requestTimeoutMs: number;\n connectTimeoutMs: number;\n signal: AbortSignal;\n }) {\n this.name = params.name;\n this.id = params.id;\n this.description = params.description;\n this.url = params.url;\n this.headers = params.headers;\n this.signal = params.signal;\n this.sessionId = params.sessionId;\n this.resolvedTransportType = params.transportType;\n this.requestTimeoutMs = params.requestTimeoutMs;\n this.connectTimeoutMs = params.connectTimeoutMs;\n this.logger = params.logger;\n this.tracing = params.tracing ?? NOOP_AGENT_TRACING;\n this.traceUrl = redactUrlForTrace(params.url);\n }\n\n getSessionId(): string | undefined {\n return this.sessionId ?? undefined;\n }\n\n private get connection(): RemoteMcpConnection {\n if (!this._connection) {\n throw new Error(`Remote MCP '${this.name}' not connected - connectIfNeeded() must run first`);\n }\n return this._connection;\n }\n\n private async resetConnection(): Promise<void> {\n this.isConnected = false;\n this.sessionId = undefined;\n this.cachedTools = undefined;\n this.connectPromise = undefined;\n await this.closeAndClearConnection();\n }\n\n private async closeAndClearConnection(): Promise<void> {\n await this._connection?.close().catch(() => {\n /* no-op */\n });\n this._connection = undefined;\n }\n\n private async resolveHeaders(): Promise<ResolveHeadersResult> {\n if (typeof this.headers !== 'function') {\n return { headers: this.headers };\n }\n return await this.headers();\n }\n\n private async executeWithSessionRetry<T>(operation: () => Promise<T>): Promise<ExecuteResult<T>> {\n // Auth is re-checked on every operation, not only on the first connect: a registered server's OAuth\n // can be revoked or expire mid-request, and callers must get authRequired rather than a generic\n // upstream failure. When already connected the resolved headers are unused (connect is skipped).\n const headersResult = await this.resolveHeaders();\n if ('authRequired' in headersResult) {\n return { authRequired: headersResult.authRequired };\n }\n return this.connectAndRun(headersResult.headers, operation, true);\n }\n\n private async connectAndRun<T>(\n headers: Record<string, string>,\n operation: () => Promise<T>,\n canRetry: boolean,\n ): Promise<ExecuteResult<T>> {\n try {\n const initInfo = await this.connectIfNeeded(headers);\n return { result: await operation(), wasInitialized: initInfo };\n } catch (error) {\n if (canRetry && isSessionExpiredError(error)) {\n this.logger.info(`Session expired for remote MCP ${this.name}, reinitializing...`);\n await this.resetConnection();\n return this.connectAndRun(headers, operation, false);\n }\n throw error;\n }\n }\n\n private async loadTools(): Promise<{ tools: AgentToolSchema[] }> {\n return this.tracing.withRemoteMcpToolSpan(\n { method: 'tools/list', serverName: this.name, serverId: this.id, serverUrl: this.traceUrl, enabled: true },\n async span => {\n const tools = await paginateWithCursorGuard(\n async cursor => {\n const page = await this.connection.listTools(cursor);\n return { items: page.tools, nextCursor: page.nextCursor };\n },\n this.name,\n this.logger,\n );\n this.cachedTools = tools.map(t => ({ ...t, preload: true }));\n span.setNumberOfTools(this.cachedTools.length);\n return { tools: this.cachedTools };\n },\n );\n }\n\n /** Unfiltered tool list (no policy). The per-agent wrapper applies selectors on top. */\n async listTools(): Promise<ListToolsResolvedResponse | AuthRequiredResponse> {\n if (this.cachedTools) {\n return { result: { tools: this.cachedTools }, wasInitialized: undefined };\n }\n const response = await this.executeWithSessionRetry(() => this.loadTools());\n if ('authRequired' in response) {\n return response;\n }\n return { result: { tools: response.result.tools }, wasInitialized: response.wasInitialized };\n }\n\n async callTool(params: CallToolRequest['params']): Promise<CallToolResolvedResponse | AuthRequiredResponse> {\n const response = await this.executeWithSessionRetry(() =>\n this.tracing.withRemoteMcpToolSpan(\n {\n method: 'tools/call',\n serverName: this.name,\n serverId: this.id,\n serverUrl: this.traceUrl,\n toolName: params.name,\n input: JSON.stringify(params.arguments),\n enabled: true,\n },\n async span => {\n const result = await this.connection.callTool(params);\n span.setOutput(JSON.stringify(result));\n return result;\n },\n ),\n );\n if ('authRequired' in response) {\n return response;\n }\n return { result: response.result, wasInitialized: response.wasInitialized };\n }\n\n toolCallInfo(params: CallToolRequest['params'], _resolveUnderlyingTool?: boolean): Promise<InternalToolCallInfo> {\n void _resolveUnderlyingTool;\n return Promise.resolve({\n type: 'mcp',\n original_tool_name: params.name,\n mcp_server_id: this.id,\n mcp_server_name: this.name,\n is_approval_required: false,\n });\n }\n\n private async connectIfNeeded(headers: Record<string, string>): Promise<MCPServerInitInfo | undefined> {\n if (this.isConnected) {\n return undefined;\n }\n if (this.connectPromise) {\n // Wait for the in-flight connect, but only its originator emits the init metadata.\n await this.connectPromise;\n return undefined;\n }\n\n const existingSessionId = this.sessionId;\n this.connectPromise = (async (): Promise<MCPServerInitInfo | undefined> => {\n let connection: RemoteMcpConnection;\n try {\n await this.closeAndClearConnection();\n connection = await this.tracing.withRemoteMcpToolSpan(\n { method: 'initialize', serverName: this.name, serverId: this.id, serverUrl: this.traceUrl, enabled: true },\n async span => {\n const conn = await connectRemoteMcp({\n url: this.url,\n headers,\n sessionId: this.sessionId ?? undefined,\n // Hint from a prior connect\n knownTransportType: this.resolvedTransportType,\n requestTimeoutMs: this.requestTimeoutMs,\n connectTimeoutMs: this.connectTimeoutMs,\n signal: this.signal,\n onClose: () => {\n this.isConnected = false;\n },\n onError: error => {\n this.logger.error(`Error on remote MCP transport ${this.name}`, { error });\n },\n });\n span.setOutput(JSON.stringify({ transport: conn.transportType, stateful: conn.sessionId !== null }));\n return conn;\n },\n );\n } catch (error) {\n await this.closeAndClearConnection();\n throw this.toConnectError(error);\n }\n this._connection = connection;\n this.resolvedTransportType = connection.transportType;\n this.isConnected = true;\n this.sessionId = connection.sessionId;\n if (existingSessionId === this.sessionId) {\n return undefined;\n }\n return {\n name: this.name,\n id: this.id,\n session_id: this.sessionId ?? undefined,\n transport_type: this.resolvedTransportType,\n };\n })().finally(() => {\n this.connectPromise = undefined;\n });\n return this.connectPromise;\n }\n\n private toConnectError(error: unknown): McpConnectionError {\n const statusCode = error instanceof McpConnectionError ? error.statusCode : 502;\n const message = error instanceof Error ? error.message : String(error);\n return new McpConnectionError(`Failed to connect to remote MCP server '${this.name}': ${message}`, statusCode, {\n cause: error,\n });\n }\n}\n"],"mappings":";AAEA,SAAS,0BAA0B;AAInC,SAAS,0BAA0B;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eAAO;AAAA,MACT;AACA,aAAO;AAAA,QACL,MAAM,KAAK;AAAA,QACX,IAAI,KAAK;AAAA,QACT,YAAY,KAAK,aAAa;AAAA,QAC9B,gBAAgB,KAAK;AAAA,MACvB;AAAA,IACF,GAAG,EAAE,QAAQ,MAAM;AACjB,WAAK,iBAAiB;AAAA,IACxB,CAAC;AACD,WAAO,KAAK;AAAA,EACd;AAAA,EAEQ,eAAe,OAAoC;AACzD,UAAM,aAAa,iBAAiB,qBAAqB,MAAM,aAAa;AAC5E,UAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACrE,WAAO,IAAI,mBAAmB,2CAA2C,KAAK,IAAI,MAAM,OAAO,IAAI,YAAY;AAAA,MAC7G,OAAO;AAAA,IACT,CAAC;AAAA,EACH;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../../src/core/mcp/RemoteMCP.ts"],"sourcesContent":["import type { CallToolRequest } from '@modelcontextprotocol/sdk/types.js';\nimport type { Logger } from 'winston';\nimport { McpConnectionError } from '../errors';\nimport type { MCPServerInitInfo } from '../events/schema';\nimport type { InternalToolCallInfo } from '../llm/LLMTypes';\nimport type { AgentTracing } from '../tracing/AgentTracing';\nimport { NOOP_AGENT_TRACING } from '../tracing/NoopAgentTracing';\nimport { extractErrorLogFields } from '../util/errorLogFields';\nimport {\n type AgentToolSchema,\n type AuthRequiredResponse,\n type CallToolResolvedResponse,\n type ListToolsResolvedResponse,\n type MCPAuthRequired,\n type ToolSource,\n} from './IMCPServer';\nimport { paginateWithCursorGuard } from './pagination';\nimport {\n connectRemoteMcp,\n isSessionExpiredError,\n type RemoteMcpConnection,\n type RemoteMcpTransportType,\n} from './remoteMcpClient';\n\n/** Redacted url for trace spans: scheme + host + path only, so userinfo/query secrets never leak. */\nfunction redactUrlForTrace(url: string): string {\n try {\n const u = new URL(url);\n return `${u.protocol}//${u.host}${u.pathname}`;\n } catch {\n return '';\n }\n}\n\n/** What a headers resolver returns: the headers to send, or a signal that auth is required. */\nexport type ResolveHeadersResult = { headers: Record<string, string> } | { authRequired: MCPAuthRequired };\n\n/** Static headers, or a resolver (invoked at connect) returning headers or signalling auth-required. */\nexport type RemoteMcpHeaders = Record<string, string> | (() => Promise<ResolveHeadersResult>);\n\ntype ExecuteResult<T> = { result: T; wasInitialized: MCPServerInitInfo | undefined } | AuthRequiredResponse;\n\n/**\n * Connection/session half of a remote MCP server: owns the transport (connects itself from `url` +\n * `headers`), session id, raw tool cache, connect single-flight and session-expiry retry. Policy-free\n * — a per-agent {@link ToolSet} layers policy.\n */\nexport class RemoteMCP implements ToolSource {\n readonly name: string;\n readonly id: string;\n readonly description?: string | undefined;\n\n private readonly url: string;\n private readonly headers: RemoteMcpHeaders;\n private readonly signal: AbortSignal;\n private readonly logger: Logger;\n private readonly tracing: AgentTracing;\n private readonly requestTimeoutMs: number;\n private readonly connectTimeoutMs: number;\n // Redacted display url for trace spans (derived from url; unused when tracing is a no-op).\n private readonly traceUrl: string;\n\n private _connection?: RemoteMcpConnection | undefined;\n private isConnected = false;\n private connectPromise: Promise<MCPServerInitInfo | undefined> | undefined;\n // undefined = never connected, string = stateful session id, null = stateless/SSE.\n private sessionId: string | null | undefined;\n private resolvedTransportType?: RemoteMcpTransportType | undefined;\n private cachedTools?: AgentToolSchema[] | undefined;\n\n constructor(params: {\n name: string;\n id: string;\n description?: string | undefined;\n url: string;\n headers: RemoteMcpHeaders;\n logger: Logger;\n tracing?: AgentTracing | undefined;\n sessionId?: string | undefined;\n transportType?: RemoteMcpTransportType | undefined;\n requestTimeoutMs: number;\n connectTimeoutMs: number;\n signal: AbortSignal;\n }) {\n this.name = params.name;\n this.id = params.id;\n this.description = params.description;\n this.url = params.url;\n this.headers = params.headers;\n this.signal = params.signal;\n this.sessionId = params.sessionId;\n this.resolvedTransportType = params.transportType;\n this.requestTimeoutMs = params.requestTimeoutMs;\n this.connectTimeoutMs = params.connectTimeoutMs;\n this.logger = params.logger;\n this.tracing = params.tracing ?? NOOP_AGENT_TRACING;\n this.traceUrl = redactUrlForTrace(params.url);\n }\n\n getSessionId(): string | undefined {\n return this.sessionId ?? undefined;\n }\n\n private get connection(): RemoteMcpConnection {\n if (!this._connection) {\n throw new Error(`Remote MCP '${this.name}' not connected - connectIfNeeded() must run first`);\n }\n return this._connection;\n }\n\n private async resetConnection(): Promise<void> {\n this.isConnected = false;\n this.sessionId = undefined;\n this.cachedTools = undefined;\n this.connectPromise = undefined;\n await this.closeAndClearConnection();\n }\n\n private async closeAndClearConnection(): Promise<void> {\n await this._connection?.close().catch(() => {\n /* no-op */\n });\n this._connection = undefined;\n }\n\n private async resolveHeaders(): Promise<ResolveHeadersResult> {\n if (typeof this.headers !== 'function') {\n return { headers: this.headers };\n }\n return await this.headers();\n }\n\n private async executeWithSessionRetry<T>(operation: () => Promise<T>): Promise<ExecuteResult<T>> {\n // Auth is re-checked on every operation, not only on the first connect: a registered server's OAuth\n // can be revoked or expire mid-request, and callers must get authRequired rather than a generic\n // upstream failure. When already connected the resolved headers are unused (connect is skipped).\n const headersResult = await this.resolveHeaders();\n if ('authRequired' in headersResult) {\n return { authRequired: headersResult.authRequired };\n }\n return this.connectAndRun(headersResult.headers, operation, true);\n }\n\n private async connectAndRun<T>(\n headers: Record<string, string>,\n operation: () => Promise<T>,\n canRetry: boolean,\n ): Promise<ExecuteResult<T>> {\n try {\n const initInfo = await this.connectIfNeeded(headers);\n return { result: await operation(), wasInitialized: initInfo };\n } catch (error) {\n if (canRetry && isSessionExpiredError(error)) {\n this.logger.info(`Session expired for remote MCP ${this.name}, reinitializing...`);\n await this.resetConnection();\n return this.connectAndRun(headers, operation, false);\n }\n throw error;\n }\n }\n\n private async loadTools(): Promise<{ tools: AgentToolSchema[] }> {\n return this.tracing.withRemoteMcpToolSpan(\n { method: 'tools/list', serverName: this.name, serverId: this.id, serverUrl: this.traceUrl, enabled: true },\n async span => {\n const tools = await paginateWithCursorGuard(\n async cursor => {\n const page = await this.connection.listTools(cursor);\n return { items: page.tools, nextCursor: page.nextCursor };\n },\n this.name,\n this.logger,\n );\n this.cachedTools = tools.map(t => ({ ...t, preload: true }));\n span.setNumberOfTools(this.cachedTools.length);\n return { tools: this.cachedTools };\n },\n );\n }\n\n /** Unfiltered tool list (no policy). The per-agent wrapper applies selectors on top. */\n async listTools(): Promise<ListToolsResolvedResponse | AuthRequiredResponse> {\n if (this.cachedTools) {\n return { result: { tools: this.cachedTools }, wasInitialized: undefined };\n }\n const response = await this.executeWithSessionRetry(() => this.loadTools());\n if ('authRequired' in response) {\n return response;\n }\n return { result: { tools: response.result.tools }, wasInitialized: response.wasInitialized };\n }\n\n async callTool(params: CallToolRequest['params']): Promise<CallToolResolvedResponse | AuthRequiredResponse> {\n const response = await this.executeWithSessionRetry(() =>\n this.tracing.withRemoteMcpToolSpan(\n {\n method: 'tools/call',\n serverName: this.name,\n serverId: this.id,\n serverUrl: this.traceUrl,\n toolName: params.name,\n input: JSON.stringify(params.arguments),\n enabled: true,\n },\n async span => {\n const result = await this.connection.callTool(params);\n span.setOutput(JSON.stringify(result));\n return result;\n },\n ),\n );\n if ('authRequired' in response) {\n return response;\n }\n return { result: response.result, wasInitialized: response.wasInitialized };\n }\n\n toolCallInfo(params: CallToolRequest['params'], _resolveUnderlyingTool?: boolean): Promise<InternalToolCallInfo> {\n void _resolveUnderlyingTool;\n return Promise.resolve({\n type: 'mcp',\n original_tool_name: params.name,\n mcp_server_id: this.id,\n mcp_server_name: this.name,\n is_approval_required: false,\n });\n }\n\n private async connectIfNeeded(headers: Record<string, string>): Promise<MCPServerInitInfo | undefined> {\n if (this.isConnected) {\n return undefined;\n }\n if (this.connectPromise) {\n // Wait for the in-flight connect, but only its originator emits the init metadata.\n await this.connectPromise;\n return undefined;\n }\n\n const existingSessionId = this.sessionId;\n this.connectPromise = (async (): Promise<MCPServerInitInfo | undefined> => {\n let connection: RemoteMcpConnection;\n try {\n await this.closeAndClearConnection();\n connection = await this.tracing.withRemoteMcpToolSpan(\n { method: 'initialize', serverName: this.name, serverId: this.id, serverUrl: this.traceUrl, enabled: true },\n async span => {\n const conn = await connectRemoteMcp({\n url: this.url,\n headers,\n sessionId: this.sessionId ?? undefined,\n // Hint from a prior connect\n knownTransportType: this.resolvedTransportType,\n requestTimeoutMs: this.requestTimeoutMs,\n connectTimeoutMs: this.connectTimeoutMs,\n signal: this.signal,\n onClose: () => {\n this.isConnected = false;\n },\n onError: error => {\n const fields = extractErrorLogFields(error);\n const msg = `Error on remote MCP transport ${this.name}`;\n if (fields.error.includes('Body Timeout')) {\n this.logger.warn(msg, fields);\n } else {\n this.logger.error(msg, fields);\n }\n },\n });\n span.setOutput(JSON.stringify({ transport: conn.transportType, stateful: conn.sessionId !== null }));\n return conn;\n },\n );\n } catch (error) {\n await this.closeAndClearConnection();\n throw this.toConnectError(error);\n }\n this._connection = connection;\n this.resolvedTransportType = connection.transportType;\n this.isConnected = true;\n this.sessionId = connection.sessionId;\n if (existingSessionId === this.sessionId) {\n return undefined;\n }\n return {\n name: this.name,\n id: this.id,\n session_id: this.sessionId ?? undefined,\n transport_type: this.resolvedTransportType,\n };\n })().finally(() => {\n this.connectPromise = undefined;\n });\n return this.connectPromise;\n }\n\n private toConnectError(error: unknown): McpConnectionError {\n const statusCode = error instanceof McpConnectionError ? error.statusCode : 502;\n const message = error instanceof Error ? error.message : String(error);\n return new McpConnectionError(`Failed to connect to remote MCP server '${this.name}': ${message}`, statusCode, {\n cause: error,\n });\n }\n}\n"],"mappings":";AAEA,SAAS,0BAA0B;AAInC,SAAS,0BAA0B;AACnC,SAAS,6BAA6B;AACtC,OAOO;AACP,SAAS,+BAA+B;AACxC;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AAGP,SAAS,kBAAkB,KAAqB;AAC9C,MAAI;AACF,UAAM,IAAI,IAAI,IAAI,GAAG;AACrB,WAAO,GAAG,EAAE,QAAQ,KAAK,EAAE,IAAI,GAAG,EAAE,QAAQ;AAAA,EAC9C,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AA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C9B,gBAAgB,KAAK;AAAA,MACvB;AAAA,IACF,GAAG,EAAE,QAAQ,MAAM;AACjB,WAAK,iBAAiB;AAAA,IACxB,CAAC;AACD,WAAO,KAAK;AAAA,EACd;AAAA,EAEQ,eAAe,OAAoC;AACzD,UAAM,aAAa,iBAAiB,qBAAqB,MAAM,aAAa;AAC5E,UAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACrE,WAAO,IAAI,mBAAmB,2CAA2C,KAAK,IAAI,MAAM,OAAO,IAAI,YAAY;AAAA,MAC7G,OAAO;AAAA,IACT,CAAC;AAAA,EACH;AACF;","names":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"remoteMcpClient.d.ts","sourceRoot":"","sources":["../../../src/core/mcp/remoteMcpClient.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"remoteMcpClient.d.ts","sourceRoot":"","sources":["../../../src/core/mcp/remoteMcpClient.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,oCAAoC,CAAC;AAK1F,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAE/C,iGAAiG;AAEjG,MAAM,MAAM,sBAAsB,GAAG,iBAAiB,GAAG,KAAK,CAAC;AAE/D,MAAM,WAAW,mBAAmB;IAClC,QAAQ,CAAC,aAAa,EAAE,sBAAsB,CAAC;IAC/C,qEAAqE;IACrE,QAAQ,CAAC,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;IAClC,SAAS,CAAC,MAAM,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC;QAAE,KAAK,EAAE,UAAU,EAAE,CAAC;QAAC,UAAU,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;KAAE,CAAC,CAAC;IAC9F,QAAQ,CAAC,MAAM,EAAE,eAAe,CAAC,QAAQ,CAAC,GAAG,OAAO,CAAC,cAAc,CAAC,CAAC;IACrE,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CACxB;AAiDD,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAQ7D;AAgED;;;;;;;GAOG;AACH,wBAAsB,gBAAgB,CAAC,MAAM,EAAE;IAC7C,GAAG,EAAE,MAAM,CAAC;IACZ,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAChC,SAAS,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC/B,kBAAkB,CAAC,EAAE,sBAAsB,GAAG,SAAS,CAAC;IACxD,gBAAgB,EAAE,MAAM,CAAC;IACzB,gBAAgB,EAAE,MAAM,CAAC;IACzB,MAAM,EAAE,WAAW,CAAC;IACpB,OAAO,CAAC,EAAE,CAAC,MAAM,IAAI,CAAC,GAAG,SAAS,CAAC;IACnC,OAAO,CAAC,EAAE,CAAC,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC,GAAG,SAAS,CAAC;CAChD,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAmD/B"}
|
|
@@ -28,10 +28,14 @@ var import_client = require("@modelcontextprotocol/sdk/client/index.js");
|
|
|
28
28
|
var import_sse = require("@modelcontextprotocol/sdk/client/sse.js");
|
|
29
29
|
var import_streamableHttp = require("@modelcontextprotocol/sdk/client/streamableHttp.js");
|
|
30
30
|
var import_api = require("@opentelemetry/api");
|
|
31
|
+
var import_undici = require("undici");
|
|
31
32
|
var import_errors = require("../errors.js");
|
|
32
33
|
var import_promiseUtils = require("../util/promiseUtils.js");
|
|
33
34
|
var CLIENT_INFO = { name: "tfy-agent-mcp-client", version: "1.0.0" };
|
|
34
35
|
var TRANSPORT_PROBE_ORDER = ["streamable-http", "sse"];
|
|
36
|
+
var MCP_BODY_TIMEOUT_MS = 30 * 60 * 1e3;
|
|
37
|
+
var mcpHttpAgent = new import_undici.Agent({ bodyTimeout: MCP_BODY_TIMEOUT_MS });
|
|
38
|
+
var mcpFetch = (url, init) => (0, import_undici.fetch)(typeof url === "string" ? url : url.href, { ...init, dispatcher: mcpHttpAgent });
|
|
35
39
|
var McpClientWithTimeout = class extends import_client.Client {
|
|
36
40
|
constructor(requestTimeoutMs) {
|
|
37
41
|
super(CLIENT_INFO, { capabilities: {} });
|
|
@@ -47,9 +51,13 @@ var McpClientWithTimeout = class extends import_client.Client {
|
|
|
47
51
|
function createTransport(type, url, headers, sessionId) {
|
|
48
52
|
const requestInit = { headers };
|
|
49
53
|
if (type === "streamable-http") {
|
|
50
|
-
return new import_streamableHttp.StreamableHTTPClientTransport(url, {
|
|
54
|
+
return new import_streamableHttp.StreamableHTTPClientTransport(url, {
|
|
55
|
+
requestInit,
|
|
56
|
+
fetch: mcpFetch,
|
|
57
|
+
...sessionId !== void 0 ? { sessionId } : {}
|
|
58
|
+
});
|
|
51
59
|
}
|
|
52
|
-
return new import_sse.SSEClientTransport(url, { requestInit });
|
|
60
|
+
return new import_sse.SSEClientTransport(url, { requestInit, fetch: mcpFetch });
|
|
53
61
|
}
|
|
54
62
|
function isSessionExpiredError(error) {
|
|
55
63
|
if (!(error instanceof Error)) {
|
|
@@ -117,16 +125,19 @@ async function connectRemoteMcp(params) {
|
|
|
117
125
|
for (const transportType of candidates) {
|
|
118
126
|
const transport = createTransport(transportType, url, params.headers, params.sessionId);
|
|
119
127
|
const client = new McpClientWithTimeout(params.requestTimeoutMs);
|
|
128
|
+
const timeout = new AbortController();
|
|
129
|
+
const connectOptions = { signal: AbortSignal.any([params.signal, timeout.signal]) };
|
|
120
130
|
try {
|
|
121
131
|
stampTraceHeaders(params.headers);
|
|
122
132
|
await (0, import_promiseUtils.withTimeout)(
|
|
123
133
|
// Concrete transports use sessionId: string|undefined; Transport uses an optional
|
|
124
134
|
// property — exactOptionalPropertyTypes rejects assignability without this cast.
|
|
125
|
-
client.connect(transport,
|
|
135
|
+
client.connect(transport, connectOptions),
|
|
126
136
|
params.connectTimeoutMs,
|
|
127
137
|
transportType
|
|
128
138
|
);
|
|
129
139
|
} catch (error) {
|
|
140
|
+
timeout.abort();
|
|
130
141
|
await client.close().catch(() => {
|
|
131
142
|
});
|
|
132
143
|
if (isAuthError(error)) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/core/mcp/remoteMcpClient.ts"],"sourcesContent":["import { Client } from '@modelcontextprotocol/sdk/client/index.js';\n// SSE remains required during the Streamable HTTP migration (some servers still speak SSE only).\n\nimport { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js';\nimport { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';\nimport type { CallToolRequest, CallToolResult } from '@modelcontextprotocol/sdk/types.js';\nimport { context, propagation } from '@opentelemetry/api';\nimport { McpConnectionError } from '../errors';\nimport { withTimeout } from '../util/promiseUtils';\nimport type { ToolSchema } from './IMCPServer';\n\n/** Networking for remote (url-based) MCP servers, kept separate so it can be mocked in tests. */\n\nexport type RemoteMcpTransportType = 'streamable-http' | 'sse';\n\nexport interface RemoteMcpConnection {\n readonly transportType: RemoteMcpTransportType;\n /** Session id for a stateful server, or null for a stateless one. */\n readonly sessionId: string | null;\n listTools(cursor?: string): Promise<{ tools: ToolSchema[]; nextCursor?: string | undefined }>;\n callTool(params: CallToolRequest['params']): Promise<CallToolResult>;\n close(): Promise<void>;\n}\n\n// SSE transport type kept for dual-probe support during migration.\n// eslint-disable-next-line @typescript-eslint/no-deprecated -- see TRANSPORT_PROBE_ORDER\ntype McpTransport = StreamableHTTPClientTransport | SSEClientTransport;\n\nconst CLIENT_INFO = { name: 'tfy-agent-mcp-client', version: '1.0.0' } as const;\nconst TRANSPORT_PROBE_ORDER: RemoteMcpTransportType[] = ['streamable-http', 'sse'];\n\nclass McpClientWithTimeout extends Client {\n constructor(private readonly requestTimeoutMs: number) {\n super(CLIENT_INFO, { capabilities: {} });\n }\n\n // SDK Client.request is loosely typed; forward with an explicit timeout.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- MCP SDK request typing\n override request(req: any, schema: any, options?: any): Promise<any> {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument -- MCP SDK request typing\n return super.request(req, schema, { ...options, timeout: this.requestTimeoutMs });\n }\n}\n\nfunction createTransport(\n type: RemoteMcpTransportType,\n url: URL,\n headers: Record<string, string>,\n sessionId?: string,\n): McpTransport {\n const requestInit = { headers };\n if (type === 'streamable-http') {\n return new StreamableHTTPClientTransport(url, { requestInit, ...(sessionId !== undefined ? { sessionId } : {}) });\n }\n // eslint-disable-next-line @typescript-eslint/no-deprecated -- dual-transport probe; see TRANSPORT_PROBE_ORDER\n return new SSEClientTransport(url, { requestInit });\n}\n\nexport function isSessionExpiredError(error: unknown): boolean {\n if (!(error instanceof Error)) {\n return false;\n }\n if ('code' in error && error.code === 404) {\n return true;\n }\n return error.message.includes('HTTP 404') || error.message.toLowerCase().includes('session');\n}\n\nfunction isAuthError(error: unknown): boolean {\n if (!(error instanceof Error)) {\n return false;\n }\n if ('code' in error && error.code === 401) {\n return true;\n }\n return error.message.includes('HTTP 401');\n}\n\n/** Inject the active otel trace context so each request propagates its span. */\nfunction stampTraceHeaders(headers: Record<string, string>): void {\n propagation.inject(context.active(), headers);\n}\n\nfunction getTransportSessionId(transport: McpTransport): string | null {\n return transport instanceof StreamableHTTPClientTransport ? (transport.sessionId ?? null) : null;\n}\n\nfunction toConnectError(error: unknown): McpConnectionError {\n if (error instanceof McpConnectionError) {\n return error;\n }\n if (isAuthError(error)) {\n return new McpConnectionError('upstream returned 401 Unauthorized', 401, {\n cause: error,\n });\n }\n const message = error instanceof Error ? error.message : String(error);\n return new McpConnectionError(message, 502, { cause: error });\n}\n\nfunction buildConnection(\n client: McpClientWithTimeout,\n transport: McpTransport,\n transportType: RemoteMcpTransportType,\n headers: Record<string, string>,\n requestOptions: { signal: AbortSignal },\n): RemoteMcpConnection {\n return {\n transportType,\n sessionId: getTransportSessionId(transport),\n listTools: async (cursor?: string) => {\n stampTraceHeaders(headers);\n const response = await client.listTools(cursor ? { cursor } : undefined, requestOptions);\n return {\n tools: response.tools,\n nextCursor: response.nextCursor,\n };\n },\n callTool: async (callParams: CallToolRequest['params']): Promise<CallToolResult> => {\n stampTraceHeaders(headers);\n return (await client.callTool(callParams, undefined, requestOptions)) as CallToolResult;\n },\n close: async (): Promise<void> => {\n await client.close().catch(() => {\n /* no-op */\n });\n },\n };\n}\n\n/**\n * Connect to a remote MCP server, keeping the first transport that connects. `sessionId` is passed to\n * every attempt so a stateful session resumes in place instead of opening a throwaway one.\n *\n * `knownTransportType` is a hint (from a prior connect / persisted state): it's tried first for a fast\n * path, but on failure we still fall back to probing the remaining transports, so a stale or wrong\n * hint (server switched transports, bad resume data) self-heals instead of failing every turn.\n */\nexport async function connectRemoteMcp(params: {\n url: string;\n headers: Record<string, string>;\n sessionId?: string | undefined;\n knownTransportType?: RemoteMcpTransportType | undefined;\n requestTimeoutMs: number;\n connectTimeoutMs: number;\n signal: AbortSignal;\n onClose?: (() => void) | undefined;\n onError?: ((error: Error) => void) | undefined;\n}): Promise<RemoteMcpConnection> {\n const url = new URL(params.url);\n const requestOptions = { signal: params.signal };\n const candidates = params.knownTransportType\n ? [params.knownTransportType, ...TRANSPORT_PROBE_ORDER.filter(t => t !== params.knownTransportType)]\n : TRANSPORT_PROBE_ORDER;\n const failures: { transport: RemoteMcpTransportType; error: string }[] = [];\n\n for (const transportType of candidates) {\n const transport = createTransport(transportType, url, params.headers, params.sessionId);\n const client = new McpClientWithTimeout(params.requestTimeoutMs);\n try {\n stampTraceHeaders(params.headers);\n await withTimeout(\n // Concrete transports use sessionId: string|undefined; Transport uses an optional\n // property — exactOptionalPropertyTypes rejects assignability without this cast.\n client.connect(transport as Parameters<Client['connect']>[0], requestOptions),\n params.connectTimeoutMs,\n transportType,\n );\n } catch (error) {\n await client.close().catch(() => {\n /* no-op */\n });\n if (isAuthError(error)) {\n throw toConnectError(error);\n }\n // A session-expired error means the transport is right but the session is stale: surface it so\n // the caller reconnects fresh instead of falling through to a different transport.\n if (params.sessionId && isSessionExpiredError(error)) {\n throw toConnectError(error);\n }\n failures.push({ transport: transportType, error: error instanceof Error ? error.message.trim() : String(error) });\n continue;\n }\n\n // Set on the client (not the transport) so the SDK's own onclose/onerror cleanup still runs; the\n // SDK invokes these from inside it. Only wired on the kept connection, so failed attempts stay quiet.\n client.onclose = () => params.onClose?.();\n client.onerror = error => params.onError?.(error);\n return buildConnection(client, transport, transportType, params.headers, requestOptions);\n }\n\n throw new McpConnectionError(`failed to connect (tried ${candidates.join(', ')}): ${JSON.stringify(failures)}`, 502);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAAuB;AAGvB,iBAAmC;AACnC,4BAA8C;AAE9C,iBAAqC;AACrC,oBAAmC;AACnC,0BAA4B;AAoB5B,IAAM,cAAc,EAAE,MAAM,wBAAwB,SAAS,QAAQ;AACrE,IAAM,wBAAkD,CAAC,mBAAmB,KAAK;AAEjF,IAAM,uBAAN,cAAmC,qBAAO;AAAA,EACxC,YAA6B,kBAA0B;AACrD,UAAM,aAAa,EAAE,cAAc,CAAC,EAAE,CAAC;AADZ;AAAA,EAE7B;AAAA,EAF6B;AAAA;AAAA;AAAA,EAMpB,QAAQ,KAAU,QAAa,SAA6B;AAEnE,WAAO,MAAM,QAAQ,KAAK,QAAQ,EAAE,GAAG,SAAS,SAAS,KAAK,iBAAiB,CAAC;AAAA,EAClF;AACF;AAEA,SAAS,gBACP,MACA,KACA,SACA,WACc;AACd,QAAM,cAAc,EAAE,QAAQ;AAC9B,MAAI,SAAS,mBAAmB;AAC9B,WAAO,IAAI,oDAA8B,KAAK,EAAE,aAAa,GAAI,cAAc,SAAY,EAAE,UAAU,IAAI,CAAC,EAAG,CAAC;AAAA,EAClH;AAEA,SAAO,IAAI,8BAAmB,KAAK,EAAE,YAAY,CAAC;AACpD;AAEO,SAAS,sBAAsB,OAAyB;AAC7D,MAAI,EAAE,iBAAiB,QAAQ;AAC7B,W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AC,MAAM,KAAK,UAAU,QAAQ,CAAC,IAAI,GAAG;AACrH;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../../src/core/mcp/remoteMcpClient.ts"],"sourcesContent":["import { Client } from '@modelcontextprotocol/sdk/client/index.js';\n// SSE remains required during the Streamable HTTP migration (some servers still speak SSE only).\n\nimport { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js';\nimport { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';\nimport type { FetchLike } from '@modelcontextprotocol/sdk/shared/transport.js';\nimport type { CallToolRequest, CallToolResult } from '@modelcontextprotocol/sdk/types.js';\nimport { context, propagation } from '@opentelemetry/api';\nimport { Agent, fetch as undiciFetch } from 'undici';\nimport { McpConnectionError } from '../errors';\nimport { withTimeout } from '../util/promiseUtils';\nimport type { ToolSchema } from './IMCPServer';\n\n/** Networking for remote (url-based) MCP servers, kept separate so it can be mocked in tests. */\n\nexport type RemoteMcpTransportType = 'streamable-http' | 'sse';\n\nexport interface RemoteMcpConnection {\n readonly transportType: RemoteMcpTransportType;\n /** Session id for a stateful server, or null for a stateless one. */\n readonly sessionId: string | null;\n listTools(cursor?: string): Promise<{ tools: ToolSchema[]; nextCursor?: string | undefined }>;\n callTool(params: CallToolRequest['params']): Promise<CallToolResult>;\n close(): Promise<void>;\n}\n\n// SSE transport type kept for dual-probe support during migration.\n// eslint-disable-next-line @typescript-eslint/no-deprecated -- see TRANSPORT_PROBE_ORDER\ntype McpTransport = StreamableHTTPClientTransport | SSEClientTransport;\n\nconst CLIENT_INFO = { name: 'tfy-agent-mcp-client', version: '1.0.0' } as const;\nconst TRANSPORT_PROBE_ORDER: RemoteMcpTransportType[] = ['streamable-http', 'sse'];\n\n// MCP SSE/streamable-HTTP keeps a long-lived response open that is often idle between tool calls.\n// Node fetch (undici) defaults bodyTimeout to 300s of silence, then kills the stream with\n// `Body Timeout Error` — we reconnect and the ~5m cycle repeats in logs. 30m matches the\n// Gateway idle-body window; MCP request deadlines still come from requestTimeoutMs.\nconst MCP_BODY_TIMEOUT_MS = 30 * 60 * 1000;\nconst mcpHttpAgent = new Agent({ bodyTimeout: MCP_BODY_TIMEOUT_MS });\nconst mcpFetch: FetchLike = (url, init) =>\n undiciFetch(typeof url === 'string' ? url : url.href, { ...(init as object), dispatcher: mcpHttpAgent });\n\nclass McpClientWithTimeout extends Client {\n constructor(private readonly requestTimeoutMs: number) {\n super(CLIENT_INFO, { capabilities: {} });\n }\n\n // SDK Client.request is loosely typed; forward with an explicit timeout.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- MCP SDK request typing\n override request(req: any, schema: any, options?: any): Promise<any> {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument -- MCP SDK request typing\n return super.request(req, schema, { ...options, timeout: this.requestTimeoutMs });\n }\n}\n\nfunction createTransport(\n type: RemoteMcpTransportType,\n url: URL,\n headers: Record<string, string>,\n sessionId?: string,\n): McpTransport {\n const requestInit = { headers };\n if (type === 'streamable-http') {\n return new StreamableHTTPClientTransport(url, {\n requestInit,\n fetch: mcpFetch,\n ...(sessionId !== undefined ? { sessionId } : {}),\n });\n }\n // eslint-disable-next-line @typescript-eslint/no-deprecated -- dual-transport probe; see TRANSPORT_PROBE_ORDER\n return new SSEClientTransport(url, { requestInit, fetch: mcpFetch });\n}\n\nexport function isSessionExpiredError(error: unknown): boolean {\n if (!(error instanceof Error)) {\n return false;\n }\n if ('code' in error && error.code === 404) {\n return true;\n }\n return error.message.includes('HTTP 404') || error.message.toLowerCase().includes('session');\n}\n\nfunction isAuthError(error: unknown): boolean {\n if (!(error instanceof Error)) {\n return false;\n }\n if ('code' in error && error.code === 401) {\n return true;\n }\n return error.message.includes('HTTP 401');\n}\n\n/** Inject the active otel trace context so each request propagates its span. */\nfunction stampTraceHeaders(headers: Record<string, string>): void {\n propagation.inject(context.active(), headers);\n}\n\nfunction getTransportSessionId(transport: McpTransport): string | null {\n return transport instanceof StreamableHTTPClientTransport ? (transport.sessionId ?? null) : null;\n}\n\nfunction toConnectError(error: unknown): McpConnectionError {\n if (error instanceof McpConnectionError) {\n return error;\n }\n if (isAuthError(error)) {\n return new McpConnectionError('upstream returned 401 Unauthorized', 401, {\n cause: error,\n });\n }\n const message = error instanceof Error ? error.message : String(error);\n return new McpConnectionError(message, 502, { cause: error });\n}\n\nfunction buildConnection(\n client: McpClientWithTimeout,\n transport: McpTransport,\n transportType: RemoteMcpTransportType,\n headers: Record<string, string>,\n requestOptions: { signal: AbortSignal },\n): RemoteMcpConnection {\n return {\n transportType,\n sessionId: getTransportSessionId(transport),\n listTools: async (cursor?: string) => {\n stampTraceHeaders(headers);\n const response = await client.listTools(cursor ? { cursor } : undefined, requestOptions);\n return {\n tools: response.tools,\n nextCursor: response.nextCursor,\n };\n },\n callTool: async (callParams: CallToolRequest['params']): Promise<CallToolResult> => {\n stampTraceHeaders(headers);\n return (await client.callTool(callParams, undefined, requestOptions)) as CallToolResult;\n },\n close: async (): Promise<void> => {\n await client.close().catch(() => {\n /* no-op */\n });\n },\n };\n}\n\n/**\n * Connect to a remote MCP server, keeping the first transport that connects. `sessionId` is passed to\n * every attempt so a stateful session resumes in place instead of opening a throwaway one.\n *\n * `knownTransportType` is a hint (from a prior connect / persisted state): it's tried first for a fast\n * path, but on failure we still fall back to probing the remaining transports, so a stale or wrong\n * hint (server switched transports, bad resume data) self-heals instead of failing every turn.\n */\nexport async function connectRemoteMcp(params: {\n url: string;\n headers: Record<string, string>;\n sessionId?: string | undefined;\n knownTransportType?: RemoteMcpTransportType | undefined;\n requestTimeoutMs: number;\n connectTimeoutMs: number;\n signal: AbortSignal;\n onClose?: (() => void) | undefined;\n onError?: ((error: Error) => void) | undefined;\n}): Promise<RemoteMcpConnection> {\n const url = new URL(params.url);\n const requestOptions = { signal: params.signal };\n const candidates = params.knownTransportType\n ? [params.knownTransportType, ...TRANSPORT_PROBE_ORDER.filter(t => t !== params.knownTransportType)]\n : TRANSPORT_PROBE_ORDER;\n const failures: { transport: RemoteMcpTransportType; error: string }[] = [];\n\n for (const transportType of candidates) {\n const transport = createTransport(transportType, url, params.headers, params.sessionId);\n const client = new McpClientWithTimeout(params.requestTimeoutMs);\n // withTimeout races client.connect() and does not abort it, so timed-out connects can leak\n // sockets until GC. Abort this controller on timeout so the handshake is cancelled.\n // AbortSignal.timeout cannot be cleared, and the SDK keeps the signal on initialize, so it\n // would still fire connectTimeoutMs later and cancel the live client.\n const timeout = new AbortController();\n const connectOptions = { signal: AbortSignal.any([params.signal, timeout.signal]) };\n try {\n stampTraceHeaders(params.headers);\n await withTimeout(\n // Concrete transports use sessionId: string|undefined; Transport uses an optional\n // property — exactOptionalPropertyTypes rejects assignability without this cast.\n client.connect(transport as Parameters<Client['connect']>[0], connectOptions),\n params.connectTimeoutMs,\n transportType,\n );\n } catch (error) {\n timeout.abort();\n await client.close().catch(() => {\n /* no-op */\n });\n if (isAuthError(error)) {\n throw toConnectError(error);\n }\n // A session-expired error means the transport is right but the session is stale: surface it so\n // the caller reconnects fresh instead of falling through to a different transport.\n if (params.sessionId && isSessionExpiredError(error)) {\n throw toConnectError(error);\n }\n failures.push({ transport: transportType, error: error instanceof Error ? error.message.trim() : String(error) });\n continue;\n }\n\n // Set on the client (not the transport) so the SDK's own onclose/onerror cleanup still runs; the\n // SDK invokes these from inside it. Only wired on the kept connection, so failed attempts stay quiet.\n client.onclose = () => params.onClose?.();\n client.onerror = error => params.onError?.(error);\n return buildConnection(client, transport, transportType, params.headers, requestOptions);\n }\n\n throw new McpConnectionError(`failed to connect (tried ${candidates.join(', ')}): ${JSON.stringify(failures)}`, 502);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAAuB;AAGvB,iBAAmC;AACnC,4BAA8C;AAG9C,iBAAqC;AACrC,oBAA4C;AAC5C,oBAAmC;AACnC,0BAA4B;AAoB5B,IAAM,cAAc,EAAE,MAAM,wBAAwB,SAAS,QAAQ;AACrE,IAAM,wB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sdk/client/sse.js";
|
|
4
4
|
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
|
5
5
|
import { context, propagation } from "@opentelemetry/api";
|
|
6
|
+
import { Agent, fetch as undiciFetch } from "undici";
|
|
6
7
|
import { McpConnectionError } from "../errors.mjs";
|
|
7
8
|
import { withTimeout } from "../util/promiseUtils.mjs";
|
|
8
9
|
var CLIENT_INFO = { name: "tfy-agent-mcp-client", version: "1.0.0" };
|
|
9
10
|
var TRANSPORT_PROBE_ORDER = ["streamable-http", "sse"];
|
|
11
|
+
var MCP_BODY_TIMEOUT_MS = 30 * 60 * 1e3;
|
|
12
|
+
var mcpHttpAgent = new Agent({ bodyTimeout: MCP_BODY_TIMEOUT_MS });
|
|
13
|
+
var mcpFetch = (url, init) => undiciFetch(typeof url === "string" ? url : url.href, { ...init, dispatcher: mcpHttpAgent });
|
|
10
14
|
var McpClientWithTimeout = class extends Client {
|
|
11
15
|
constructor(requestTimeoutMs) {
|
|
12
16
|
super(CLIENT_INFO, { capabilities: {} });
|
|
@@ -22,9 +26,13 @@ var McpClientWithTimeout = class extends Client {
|
|
|
22
26
|
function createTransport(type, url, headers, sessionId) {
|
|
23
27
|
const requestInit = { headers };
|
|
24
28
|
if (type === "streamable-http") {
|
|
25
|
-
return new StreamableHTTPClientTransport(url, {
|
|
29
|
+
return new StreamableHTTPClientTransport(url, {
|
|
30
|
+
requestInit,
|
|
31
|
+
fetch: mcpFetch,
|
|
32
|
+
...sessionId !== void 0 ? { sessionId } : {}
|
|
33
|
+
});
|
|
26
34
|
}
|
|
27
|
-
return new SSEClientTransport(url, { requestInit });
|
|
35
|
+
return new SSEClientTransport(url, { requestInit, fetch: mcpFetch });
|
|
28
36
|
}
|
|
29
37
|
function isSessionExpiredError(error) {
|
|
30
38
|
if (!(error instanceof Error)) {
|
|
@@ -92,16 +100,19 @@ async function connectRemoteMcp(params) {
|
|
|
92
100
|
for (const transportType of candidates) {
|
|
93
101
|
const transport = createTransport(transportType, url, params.headers, params.sessionId);
|
|
94
102
|
const client = new McpClientWithTimeout(params.requestTimeoutMs);
|
|
103
|
+
const timeout = new AbortController();
|
|
104
|
+
const connectOptions = { signal: AbortSignal.any([params.signal, timeout.signal]) };
|
|
95
105
|
try {
|
|
96
106
|
stampTraceHeaders(params.headers);
|
|
97
107
|
await withTimeout(
|
|
98
108
|
// Concrete transports use sessionId: string|undefined; Transport uses an optional
|
|
99
109
|
// property — exactOptionalPropertyTypes rejects assignability without this cast.
|
|
100
|
-
client.connect(transport,
|
|
110
|
+
client.connect(transport, connectOptions),
|
|
101
111
|
params.connectTimeoutMs,
|
|
102
112
|
transportType
|
|
103
113
|
);
|
|
104
114
|
} catch (error) {
|
|
115
|
+
timeout.abort();
|
|
105
116
|
await client.close().catch(() => {
|
|
106
117
|
});
|
|
107
118
|
if (isAuthError(error)) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/core/mcp/remoteMcpClient.ts"],"sourcesContent":["import { Client } from '@modelcontextprotocol/sdk/client/index.js';\n// SSE remains required during the Streamable HTTP migration (some servers still speak SSE only).\n\nimport { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js';\nimport { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';\nimport type { CallToolRequest, CallToolResult } from '@modelcontextprotocol/sdk/types.js';\nimport { context, propagation } from '@opentelemetry/api';\nimport { McpConnectionError } from '../errors';\nimport { withTimeout } from '../util/promiseUtils';\nimport type { ToolSchema } from './IMCPServer';\n\n/** Networking for remote (url-based) MCP servers, kept separate so it can be mocked in tests. */\n\nexport type RemoteMcpTransportType = 'streamable-http' | 'sse';\n\nexport interface RemoteMcpConnection {\n readonly transportType: RemoteMcpTransportType;\n /** Session id for a stateful server, or null for a stateless one. */\n readonly sessionId: string | null;\n listTools(cursor?: string): Promise<{ tools: ToolSchema[]; nextCursor?: string | undefined }>;\n callTool(params: CallToolRequest['params']): Promise<CallToolResult>;\n close(): Promise<void>;\n}\n\n// SSE transport type kept for dual-probe support during migration.\n// eslint-disable-next-line @typescript-eslint/no-deprecated -- see TRANSPORT_PROBE_ORDER\ntype McpTransport = StreamableHTTPClientTransport | SSEClientTransport;\n\nconst CLIENT_INFO = { name: 'tfy-agent-mcp-client', version: '1.0.0' } as const;\nconst TRANSPORT_PROBE_ORDER: RemoteMcpTransportType[] = ['streamable-http', 'sse'];\n\nclass McpClientWithTimeout extends Client {\n constructor(private readonly requestTimeoutMs: number) {\n super(CLIENT_INFO, { capabilities: {} });\n }\n\n // SDK Client.request is loosely typed; forward with an explicit timeout.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- MCP SDK request typing\n override request(req: any, schema: any, options?: any): Promise<any> {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument -- MCP SDK request typing\n return super.request(req, schema, { ...options, timeout: this.requestTimeoutMs });\n }\n}\n\nfunction createTransport(\n type: RemoteMcpTransportType,\n url: URL,\n headers: Record<string, string>,\n sessionId?: string,\n): McpTransport {\n const requestInit = { headers };\n if (type === 'streamable-http') {\n return new StreamableHTTPClientTransport(url, { requestInit, ...(sessionId !== undefined ? { sessionId } : {}) });\n }\n // eslint-disable-next-line @typescript-eslint/no-deprecated -- dual-transport probe; see TRANSPORT_PROBE_ORDER\n return new SSEClientTransport(url, { requestInit });\n}\n\nexport function isSessionExpiredError(error: unknown): boolean {\n if (!(error instanceof Error)) {\n return false;\n }\n if ('code' in error && error.code === 404) {\n return true;\n }\n return error.message.includes('HTTP 404') || error.message.toLowerCase().includes('session');\n}\n\nfunction isAuthError(error: unknown): boolean {\n if (!(error instanceof Error)) {\n return false;\n }\n if ('code' in error && error.code === 401) {\n return true;\n }\n return error.message.includes('HTTP 401');\n}\n\n/** Inject the active otel trace context so each request propagates its span. */\nfunction stampTraceHeaders(headers: Record<string, string>): void {\n propagation.inject(context.active(), headers);\n}\n\nfunction getTransportSessionId(transport: McpTransport): string | null {\n return transport instanceof StreamableHTTPClientTransport ? (transport.sessionId ?? null) : null;\n}\n\nfunction toConnectError(error: unknown): McpConnectionError {\n if (error instanceof McpConnectionError) {\n return error;\n }\n if (isAuthError(error)) {\n return new McpConnectionError('upstream returned 401 Unauthorized', 401, {\n cause: error,\n });\n }\n const message = error instanceof Error ? error.message : String(error);\n return new McpConnectionError(message, 502, { cause: error });\n}\n\nfunction buildConnection(\n client: McpClientWithTimeout,\n transport: McpTransport,\n transportType: RemoteMcpTransportType,\n headers: Record<string, string>,\n requestOptions: { signal: AbortSignal },\n): RemoteMcpConnection {\n return {\n transportType,\n sessionId: getTransportSessionId(transport),\n listTools: async (cursor?: string) => {\n stampTraceHeaders(headers);\n const response = await client.listTools(cursor ? { cursor } : undefined, requestOptions);\n return {\n tools: response.tools,\n nextCursor: response.nextCursor,\n };\n },\n callTool: async (callParams: CallToolRequest['params']): Promise<CallToolResult> => {\n stampTraceHeaders(headers);\n return (await client.callTool(callParams, undefined, requestOptions)) as CallToolResult;\n },\n close: async (): Promise<void> => {\n await client.close().catch(() => {\n /* no-op */\n });\n },\n };\n}\n\n/**\n * Connect to a remote MCP server, keeping the first transport that connects. `sessionId` is passed to\n * every attempt so a stateful session resumes in place instead of opening a throwaway one.\n *\n * `knownTransportType` is a hint (from a prior connect / persisted state): it's tried first for a fast\n * path, but on failure we still fall back to probing the remaining transports, so a stale or wrong\n * hint (server switched transports, bad resume data) self-heals instead of failing every turn.\n */\nexport async function connectRemoteMcp(params: {\n url: string;\n headers: Record<string, string>;\n sessionId?: string | undefined;\n knownTransportType?: RemoteMcpTransportType | undefined;\n requestTimeoutMs: number;\n connectTimeoutMs: number;\n signal: AbortSignal;\n onClose?: (() => void) | undefined;\n onError?: ((error: Error) => void) | undefined;\n}): Promise<RemoteMcpConnection> {\n const url = new URL(params.url);\n const requestOptions = { signal: params.signal };\n const candidates = params.knownTransportType\n ? [params.knownTransportType, ...TRANSPORT_PROBE_ORDER.filter(t => t !== params.knownTransportType)]\n : TRANSPORT_PROBE_ORDER;\n const failures: { transport: RemoteMcpTransportType; error: string }[] = [];\n\n for (const transportType of candidates) {\n const transport = createTransport(transportType, url, params.headers, params.sessionId);\n const client = new McpClientWithTimeout(params.requestTimeoutMs);\n try {\n stampTraceHeaders(params.headers);\n await withTimeout(\n // Concrete transports use sessionId: string|undefined; Transport uses an optional\n // property — exactOptionalPropertyTypes rejects assignability without this cast.\n client.connect(transport as Parameters<Client['connect']>[0], requestOptions),\n params.connectTimeoutMs,\n transportType,\n );\n } catch (error) {\n await client.close().catch(() => {\n /* no-op */\n });\n if (isAuthError(error)) {\n throw toConnectError(error);\n }\n // A session-expired error means the transport is right but the session is stale: surface it so\n // the caller reconnects fresh instead of falling through to a different transport.\n if (params.sessionId && isSessionExpiredError(error)) {\n throw toConnectError(error);\n }\n failures.push({ transport: transportType, error: error instanceof Error ? error.message.trim() : String(error) });\n continue;\n }\n\n // Set on the client (not the transport) so the SDK's own onclose/onerror cleanup still runs; the\n // SDK invokes these from inside it. Only wired on the kept connection, so failed attempts stay quiet.\n client.onclose = () => params.onClose?.();\n client.onerror = error => params.onError?.(error);\n return buildConnection(client, transport, transportType, params.headers, requestOptions);\n }\n\n throw new McpConnectionError(`failed to connect (tried ${candidates.join(', ')}): ${JSON.stringify(failures)}`, 502);\n}\n"],"mappings":";AAAA,SAAS,cAAc;AAGvB,SAAS,0BAA0B;AACnC,SAAS,qCAAqC;AAE9C,SAAS,SAAS,mBAAmB;AACrC,SAAS,0BAA0B;AACnC,SAAS,mBAAmB;AAoB5B,IAAM,cAAc,EAAE,MAAM,wBAAwB,SAAS,QAAQ;AACrE,IAAM,wBAAkD,CAAC,mBAAmB,KAAK;AAEjF,IAAM,uBAAN,cAAmC,OAAO;AAAA,EACxC,YAA6B,kBAA0B;AACrD,UAAM,aAAa,EAAE,cAAc,CAAC,EAAE,CAAC;AADZ;AAAA,EAE7B;AAAA,EAF6B;AAAA;AAAA;AAAA,EAMpB,QAAQ,KAAU,QAAa,SAA6B;AAEnE,WAAO,MAAM,QAA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;AAGA,UAAI,OAAO,aAAa,sBAAsB,KAAK,GAAG;AACpD,cAAM,eAAe,KAAK;AAAA,MAC5B;AACA,eAAS,KAAK,EAAE,WAAW,eAAe,OAAO,iBAAiB,QAAQ,MAAM,QAAQ,KAAK,IAAI,OAAO,KAAK,EAAE,CAAC;AAChH;AAAA,IACF;AAIA,WAAO,UAAU,MAAM,OAAO,UAAU;AACxC,WAAO,UAAU,WAAS,OAAO,UAAU,KAAK;AAChD,WAAO,gBAAgB,QAAQ,WAAW,eAAe,OAAO,SAAS,cAAc;AAAA,EACzF;AAEA,QAAM,IAAI,mBAAmB,4BAA4B,WAAW,KAAK,IAAI,CAAC,MAAM,KAAK,UAAU,QAAQ,CAAC,IAAI,GAAG;AACrH;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../../src/core/mcp/remoteMcpClient.ts"],"sourcesContent":["import { Client } from '@modelcontextprotocol/sdk/client/index.js';\n// SSE remains required during the Streamable HTTP migration (some servers still speak SSE only).\n\nimport { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js';\nimport { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';\nimport type { FetchLike } from '@modelcontextprotocol/sdk/shared/transport.js';\nimport type { CallToolRequest, CallToolResult } from '@modelcontextprotocol/sdk/types.js';\nimport { context, propagation } from '@opentelemetry/api';\nimport { Agent, fetch as undiciFetch } from 'undici';\nimport { McpConnectionError } from '../errors';\nimport { withTimeout } from '../util/promiseUtils';\nimport type { ToolSchema } from './IMCPServer';\n\n/** Networking for remote (url-based) MCP servers, kept separate so it can be mocked in tests. */\n\nexport type RemoteMcpTransportType = 'streamable-http' | 'sse';\n\nexport interface RemoteMcpConnection {\n readonly transportType: RemoteMcpTransportType;\n /** Session id for a stateful server, or null for a stateless one. */\n readonly sessionId: string | null;\n listTools(cursor?: string): Promise<{ tools: ToolSchema[]; nextCursor?: string | undefined }>;\n callTool(params: CallToolRequest['params']): Promise<CallToolResult>;\n close(): Promise<void>;\n}\n\n// SSE transport type kept for dual-probe support during migration.\n// eslint-disable-next-line @typescript-eslint/no-deprecated -- see TRANSPORT_PROBE_ORDER\ntype McpTransport = StreamableHTTPClientTransport | SSEClientTransport;\n\nconst CLIENT_INFO = { name: 'tfy-agent-mcp-client', version: '1.0.0' } as const;\nconst TRANSPORT_PROBE_ORDER: RemoteMcpTransportType[] = ['streamable-http', 'sse'];\n\n// MCP SSE/streamable-HTTP keeps a long-lived response open that is often idle between tool calls.\n// Node fetch (undici) defaults bodyTimeout to 300s of silence, then kills the stream with\n// `Body Timeout Error` — we reconnect and the ~5m cycle repeats in logs. 30m matches the\n// Gateway idle-body window; MCP request deadlines still come from requestTimeoutMs.\nconst MCP_BODY_TIMEOUT_MS = 30 * 60 * 1000;\nconst mcpHttpAgent = new Agent({ bodyTimeout: MCP_BODY_TIMEOUT_MS });\nconst mcpFetch: FetchLike = (url, init) =>\n undiciFetch(typeof url === 'string' ? url : url.href, { ...(init as object), dispatcher: mcpHttpAgent });\n\nclass McpClientWithTimeout extends Client {\n constructor(private readonly requestTimeoutMs: number) {\n super(CLIENT_INFO, { capabilities: {} });\n }\n\n // SDK Client.request is loosely typed; forward with an explicit timeout.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- MCP SDK request typing\n override request(req: any, schema: any, options?: any): Promise<any> {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument -- MCP SDK request typing\n return super.request(req, schema, { ...options, timeout: this.requestTimeoutMs });\n }\n}\n\nfunction createTransport(\n type: RemoteMcpTransportType,\n url: URL,\n headers: Record<string, string>,\n sessionId?: string,\n): McpTransport {\n const requestInit = { headers };\n if (type === 'streamable-http') {\n return new StreamableHTTPClientTransport(url, {\n requestInit,\n fetch: mcpFetch,\n ...(sessionId !== undefined ? { sessionId } : {}),\n });\n }\n // eslint-disable-next-line @typescript-eslint/no-deprecated -- dual-transport probe; see TRANSPORT_PROBE_ORDER\n return new SSEClientTransport(url, { requestInit, fetch: mcpFetch });\n}\n\nexport function isSessionExpiredError(error: unknown): boolean {\n if (!(error instanceof Error)) {\n return false;\n }\n if ('code' in error && error.code === 404) {\n return true;\n }\n return error.message.includes('HTTP 404') || error.message.toLowerCase().includes('session');\n}\n\nfunction isAuthError(error: unknown): boolean {\n if (!(error instanceof Error)) {\n return false;\n }\n if ('code' in error && error.code === 401) {\n return true;\n }\n return error.message.includes('HTTP 401');\n}\n\n/** Inject the active otel trace context so each request propagates its span. */\nfunction stampTraceHeaders(headers: Record<string, string>): void {\n propagation.inject(context.active(), headers);\n}\n\nfunction getTransportSessionId(transport: McpTransport): string | null {\n return transport instanceof StreamableHTTPClientTransport ? (transport.sessionId ?? null) : null;\n}\n\nfunction toConnectError(error: unknown): McpConnectionError {\n if (error instanceof McpConnectionError) {\n return error;\n }\n if (isAuthError(error)) {\n return new McpConnectionError('upstream returned 401 Unauthorized', 401, {\n cause: error,\n });\n }\n const message = error instanceof Error ? error.message : String(error);\n return new McpConnectionError(message, 502, { cause: error });\n}\n\nfunction buildConnection(\n client: McpClientWithTimeout,\n transport: McpTransport,\n transportType: RemoteMcpTransportType,\n headers: Record<string, string>,\n requestOptions: { signal: AbortSignal },\n): RemoteMcpConnection {\n return {\n transportType,\n sessionId: getTransportSessionId(transport),\n listTools: async (cursor?: string) => {\n stampTraceHeaders(headers);\n const response = await client.listTools(cursor ? { cursor } : undefined, requestOptions);\n return {\n tools: response.tools,\n nextCursor: response.nextCursor,\n };\n },\n callTool: async (callParams: CallToolRequest['params']): Promise<CallToolResult> => {\n stampTraceHeaders(headers);\n return (await client.callTool(callParams, undefined, requestOptions)) as CallToolResult;\n },\n close: async (): Promise<void> => {\n await client.close().catch(() => {\n /* no-op */\n });\n },\n };\n}\n\n/**\n * Connect to a remote MCP server, keeping the first transport that connects. `sessionId` is passed to\n * every attempt so a stateful session resumes in place instead of opening a throwaway one.\n *\n * `knownTransportType` is a hint (from a prior connect / persisted state): it's tried first for a fast\n * path, but on failure we still fall back to probing the remaining transports, so a stale or wrong\n * hint (server switched transports, bad resume data) self-heals instead of failing every turn.\n */\nexport async function connectRemoteMcp(params: {\n url: string;\n headers: Record<string, string>;\n sessionId?: string | undefined;\n knownTransportType?: RemoteMcpTransportType | undefined;\n requestTimeoutMs: number;\n connectTimeoutMs: number;\n signal: AbortSignal;\n onClose?: (() => void) | undefined;\n onError?: ((error: Error) => void) | undefined;\n}): Promise<RemoteMcpConnection> {\n const url = new URL(params.url);\n const requestOptions = { signal: params.signal };\n const candidates = params.knownTransportType\n ? [params.knownTransportType, ...TRANSPORT_PROBE_ORDER.filter(t => t !== params.knownTransportType)]\n : TRANSPORT_PROBE_ORDER;\n const failures: { transport: RemoteMcpTransportType; error: string }[] = [];\n\n for (const transportType of candidates) {\n const transport = createTransport(transportType, url, params.headers, params.sessionId);\n const client = new McpClientWithTimeout(params.requestTimeoutMs);\n // withTimeout races client.connect() and does not abort it, so timed-out connects can leak\n // sockets until GC. Abort this controller on timeout so the handshake is cancelled.\n // AbortSignal.timeout cannot be cleared, and the SDK keeps the signal on initialize, so it\n // would still fire connectTimeoutMs later and cancel the live client.\n const timeout = new AbortController();\n const connectOptions = { signal: AbortSignal.any([params.signal, timeout.signal]) };\n try {\n stampTraceHeaders(params.headers);\n await withTimeout(\n // Concrete transports use sessionId: string|undefined; Transport uses an optional\n // property — exactOptionalPropertyTypes rejects assignability without this cast.\n client.connect(transport as Parameters<Client['connect']>[0], connectOptions),\n params.connectTimeoutMs,\n transportType,\n );\n } catch (error) {\n timeout.abort();\n await client.close().catch(() => {\n /* no-op */\n });\n if (isAuthError(error)) {\n throw toConnectError(error);\n }\n // A session-expired error means the transport is right but the session is stale: surface it so\n // the caller reconnects fresh instead of falling through to a different transport.\n if (params.sessionId && isSessionExpiredError(error)) {\n throw toConnectError(error);\n }\n failures.push({ transport: transportType, error: error instanceof Error ? error.message.trim() : String(error) });\n continue;\n }\n\n // Set on the client (not the transport) so the SDK's own onclose/onerror cleanup still runs; the\n // SDK invokes these from inside it. Only wired on the kept connection, so failed attempts stay quiet.\n client.onclose = () => params.onClose?.();\n client.onerror = error => params.onError?.(error);\n return buildConnection(client, transport, transportType, params.headers, requestOptions);\n }\n\n throw new McpConnectionError(`failed to connect (tried ${candidates.join(', ')}): ${JSON.stringify(failures)}`, 502);\n}\n"],"mappings":";AAAA,SAAS,cAAc;AAGvB,SAAS,0BAA0B;AACnC,SAAS,qCAAqC;AAG9C,SAAS,SAAS,mBAAmB;AACrC,SAAS,OAAO,SAAS,mBAAmB;AAC5C,SAAS,0BAA0B;AACnC,SAAS,mBAAmB;AAoB5B,IAAM,cAAc,EAAE,MAAM,wBAAwB,SAAS,QAAQ;AACrE,IAAM,wBAAkD,CAAC,mBAAmB,KAAK;AAMjF,IAAM,sBAAsB,KAAK,KAAK;AACtC,IAAM,eAAe,IAAI,MAAM,EAAE,aAAa,oBAAoB,CAAC;AACnE,IAAM,WAAsB,CAAC,KAAK,SAChC,YAAY,OAAO,QAAQ,WAAW,MAAM,IAAI,MAAM,EAAE,GAAI,MAAiB,YAAY,aAAa,CAAC;AAEzG,IAAM,uBAAN,cAAmC,OAAO;AAAA,EACxC,YAA6B,kBAA0B;AACrD,UAAM,aAAa,EAAE,cAAc,CAAC,EAAE,CAAC;AADZ;AAAA,EAE7B;AAAA,EAF6B;AAAA;AAAA;AAAA,EAMpB,QAAQ,KAAU,QAAa,SAA6B;AAEnE,WAAO,MAAM,QAAQ,KAAK,QAAQ,EAAE,GAAG,SAAS,SAAS,KAAK,iBAAiB,CAAC;AAAA,EAClF;AACF;AAEA,SAAS,gBACP,MACA,KACA,SACA,WACc;AACd,QAAM,cAAc,EAAE,QAAQ;AAC9B,MAAI,SAAS,mBAAmB;AAC9B,WAAO,IAAI,8BAA8B,KAAK;AAAA,MAC5C;AAAA,MACA,OAAO;AAAA,MACP,GAAI,cAAc,SAAY,EAAE,UAAU,IAAI,CAAC;AAAA,IACjD,CAAC;AAAA,EACH;AAEA,SAAO,IAAI,mBAAmB,KAAK,EAAE,aAAa,OAAO,SAA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C;AAChH;AAAA,IACF;AAIA,WAAO,UAAU,MAAM,OAAO,UAAU;AACxC,WAAO,UAAU,WAAS,OAAO,UAAU,KAAK;AAChD,WAAO,gBAAgB,QAAQ,WAAW,eAAe,OAAO,SAAS,cAAc;AAAA,EACzF;AAEA,QAAM,IAAI,mBAAmB,4BAA4B,WAAW,KAAK,IAAI,CAAC,MAAM,KAAK,UAAU,QAAQ,CAAC,IAAI,GAAG;AACrH;","names":[]}
|
|
@@ -8,8 +8,8 @@ export interface SendRequestOptions {
|
|
|
8
8
|
}
|
|
9
9
|
/**
|
|
10
10
|
* Publishes the request (JSON) on the worker channel, then polls the reply key with GETDEL
|
|
11
|
-
* (see https://redis.io/docs/latest/commands/getdel/ ) until a result arrives
|
|
12
|
-
* budget is exceeded.
|
|
11
|
+
* (see https://redis.io/docs/latest/commands/getdel/ ) until a result arrives, the executor
|
|
12
|
+
* heartbeat expires, or the wait budget is exceeded.
|
|
13
13
|
*/
|
|
14
14
|
export declare function redisRequest<T extends JSONValue>({ redis: redisClient, executorId, path, request, options, }: {
|
|
15
15
|
redis: RedisClientType;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../src/request-reply/client.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,OAAO,CAAC;AAE7C,OAAO,KAAK,EAAE,SAAS,EAAE,SAAS,EAAoB,eAAe,EAAE,MAAM,SAAS,CAAC;AAIvF,MAAM,WAAW,kBAAkB;IACjC,wEAAwE;IACxE,cAAc,EAAE,MAAM,CAAC;IACvB,0EAA0E;IAC1E,cAAc,EAAE,MAAM,CAAC;CACxB;AAyBD;;;;GAIG;AACH,wBAAsB,YAAY,CAAC,CAAC,SAAS,SAAS,EAAE,EACtD,KAAK,EAAE,WAAW,EAClB,UAAU,EACV,IAAI,EACJ,OAAO,EACP,OAAO,GACR,EAAE;IACD,KAAK,EAAE,eAAe,CAAC;IACvB,UAAU,EAAE,MAAM,CAAC;IACnB,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,eAAe,CAAC,CAAC,CAAC,CAAC;IAC5B,OAAO,CAAC,EAAE,OAAO,CAAC,kBAAkB,CAAC,GAAG,SAAS,CAAC;CACnD,GAAG,OAAO,CAAC,SAAS,CAAC,
|
|
1
|
+
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../src/request-reply/client.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,OAAO,CAAC;AAE7C,OAAO,KAAK,EAAE,SAAS,EAAE,SAAS,EAAoB,eAAe,EAAE,MAAM,SAAS,CAAC;AAIvF,MAAM,WAAW,kBAAkB;IACjC,wEAAwE;IACxE,cAAc,EAAE,MAAM,CAAC;IACvB,0EAA0E;IAC1E,cAAc,EAAE,MAAM,CAAC;CACxB;AAyBD;;;;GAIG;AACH,wBAAsB,YAAY,CAAC,CAAC,SAAS,SAAS,EAAE,EACtD,KAAK,EAAE,WAAW,EAClB,UAAU,EACV,IAAI,EACJ,OAAO,EACP,OAAO,GACR,EAAE;IACD,KAAK,EAAE,eAAe,CAAC;IACvB,UAAU,EAAE,MAAM,CAAC;IACnB,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,eAAe,CAAC,CAAC,CAAC,CAAC;IAC5B,OAAO,CAAC,EAAE,OAAO,CAAC,kBAAkB,CAAC,GAAG,SAAS,CAAC;CACnD,GAAG,OAAO,CAAC,SAAS,CAAC,CAuCrB"}
|
|
@@ -79,6 +79,9 @@ async function redisRequest({
|
|
|
79
79
|
if (replyPayload) {
|
|
80
80
|
return replyPayload;
|
|
81
81
|
}
|
|
82
|
+
if (await redisClient.exists(aliveK) === 0) {
|
|
83
|
+
throw new import_errors.NoResponderError(executorId);
|
|
84
|
+
}
|
|
82
85
|
if (import_node_perf_hooks.performance.now() >= replyDeadline) {
|
|
83
86
|
throw new import_errors.RequestTimeoutError(replyTimeoutMs);
|
|
84
87
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/request-reply/client.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\nimport { performance } from 'node:perf_hooks';\nimport type { RedisClientType } from 'redis';\nimport { NoResponderError, RequestTimeoutError } from './errors';\nimport type { JSONReply, JSONValue, PublishedRequest, RequestEnvelope } from './types';\nimport { jsonReplySchema } from './types';\nimport { heartbeatKey, replyKey, requestChannel, sleep } from './utils';\n\nexport interface SendRequestOptions {\n /** Max time to wait for a reply after the request is published (ms). */\n replyTimeoutMs: number;\n /** Sleep between poll attempts when the reply is not yet present (ms). */\n pollIntervalMs: number;\n}\n\nconst DEFAULT_REPLY_TIMEOUT_MS = 60_000;\nconst DEFAULT_POLL_INTERVAL_MS = 500;\n\nfunction resolveSendRequestOptions(options: Partial<SendRequestOptions> | undefined): SendRequestOptions {\n return {\n replyTimeoutMs: options?.replyTimeoutMs ?? DEFAULT_REPLY_TIMEOUT_MS,\n pollIntervalMs: options?.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS,\n };\n}\n\nfunction parseReplyPayload(raw: string) {\n const parsed: unknown = JSON.parse(raw);\n return jsonReplySchema.parse(parsed);\n}\n\nasync function getDelReply(redisClient: RedisClientType, rKey: string): Promise<JSONReply | null> {\n const raw = await redisClient.getDel(rKey);\n if (raw === null) {\n return null;\n }\n return parseReplyPayload(raw);\n}\n\n/**\n * Publishes the request (JSON) on the worker channel, then polls the reply key with GETDEL\n * (see https://redis.io/docs/latest/commands/getdel/ ) until a result arrives
|
|
1
|
+
{"version":3,"sources":["../../src/request-reply/client.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\nimport { performance } from 'node:perf_hooks';\nimport type { RedisClientType } from 'redis';\nimport { NoResponderError, RequestTimeoutError } from './errors';\nimport type { JSONReply, JSONValue, PublishedRequest, RequestEnvelope } from './types';\nimport { jsonReplySchema } from './types';\nimport { heartbeatKey, replyKey, requestChannel, sleep } from './utils';\n\nexport interface SendRequestOptions {\n /** Max time to wait for a reply after the request is published (ms). */\n replyTimeoutMs: number;\n /** Sleep between poll attempts when the reply is not yet present (ms). */\n pollIntervalMs: number;\n}\n\nconst DEFAULT_REPLY_TIMEOUT_MS = 60_000;\nconst DEFAULT_POLL_INTERVAL_MS = 500;\n\nfunction resolveSendRequestOptions(options: Partial<SendRequestOptions> | undefined): SendRequestOptions {\n return {\n replyTimeoutMs: options?.replyTimeoutMs ?? DEFAULT_REPLY_TIMEOUT_MS,\n pollIntervalMs: options?.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS,\n };\n}\n\nfunction parseReplyPayload(raw: string) {\n const parsed: unknown = JSON.parse(raw);\n return jsonReplySchema.parse(parsed);\n}\n\nasync function getDelReply(redisClient: RedisClientType, rKey: string): Promise<JSONReply | null> {\n const raw = await redisClient.getDel(rKey);\n if (raw === null) {\n return null;\n }\n return parseReplyPayload(raw);\n}\n\n/**\n * Publishes the request (JSON) on the worker channel, then polls the reply key with GETDEL\n * (see https://redis.io/docs/latest/commands/getdel/ ) until a result arrives, the executor\n * heartbeat expires, or the wait budget is exceeded.\n */\nexport async function redisRequest<T extends JSONValue>({\n redis: redisClient,\n executorId,\n path,\n request,\n options,\n}: {\n redis: RedisClientType;\n executorId: string;\n path: string;\n request: RequestEnvelope<T>;\n options?: Partial<SendRequestOptions> | undefined;\n}): Promise<JSONReply> {\n const { replyTimeoutMs, pollIntervalMs } = resolveSendRequestOptions(options);\n const aliveK = heartbeatKey(executorId);\n if ((await redisClient.exists(aliveK)) === 0) {\n throw new NoResponderError(executorId);\n }\n\n const requestId = randomUUID();\n const rKey = replyKey(requestId);\n const payload: PublishedRequest = {\n replyKey: rKey,\n path,\n body: request.body,\n headers: request.headers,\n };\n const serializedPayload = JSON.stringify(payload);\n const subscriberCount = await redisClient.publish(requestChannel(executorId), serializedPayload);\n if (subscriberCount === 0) {\n throw new NoResponderError(executorId, 'No executor received the published request');\n }\n\n const replyDeadline = performance.now() + replyTimeoutMs;\n // Give the executor a moment to process before the first poll.\n await sleep(Math.min(200, replyTimeoutMs));\n for (;;) {\n const replyPayload = await getDelReply(redisClient, rKey);\n if (replyPayload) {\n return replyPayload;\n }\n // We already checked that the executor was alive before sending, but it may have\n // died while we wait. Recheck here so we fail soon instead of waiting until the timeout.\n if ((await redisClient.exists(aliveK)) === 0) {\n throw new NoResponderError(executorId);\n }\n if (performance.now() >= replyDeadline) {\n throw new RequestTimeoutError(replyTimeoutMs);\n }\n await sleep(pollIntervalMs);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,yBAA2B;AAC3B,6BAA4B;AAE5B,oBAAsD;AAEtD,mBAAgC;AAChC,mBAA8D;AAS9D,IAAM,2BAA2B;AACjC,IAAM,2BAA2B;AAEjC,SAAS,0BAA0B,SAAsE;AACvG,SAAO;AAAA,IACL,gBAAgB,SAAS,kBAAkB;AAAA,IAC3C,gBAAgB,SAAS,kBAAkB;AAAA,EAC7C;AACF;AAEA,SAAS,kBAAkB,KAAa;AACtC,QAAM,SAAkB,KAAK,MAAM,GAAG;AACtC,SAAO,6BAAgB,MAAM,MAAM;AACrC;AAEA,eAAe,YAAY,aAA8B,MAAyC;AAChG,QAAM,MAAM,MAAM,YAAY,OAAO,IAAI;AACzC,MAAI,QAAQ,MAAM;AAChB,WAAO;AAAA,EACT;AACA,SAAO,kBAAkB,GAAG;AAC9B;AAOA,eAAsB,aAAkC;AAAA,EACtD,OAAO;AAAA,EACP;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAMuB;AACrB,QAAM,EAAE,gBAAgB,eAAe,IAAI,0BAA0B,OAAO;AAC5E,QAAM,aAAS,2BAAa,UAAU;AACtC,MAAK,MAAM,YAAY,OAAO,MAAM,MAAO,GAAG;AAC5C,UAAM,IAAI,+BAAiB,UAAU;AAAA,EACvC;AAEA,QAAM,gBAAY,+BAAW;AAC7B,QAAM,WAAO,uBAAS,SAAS;AAC/B,QAAM,UAA4B;AAAA,IAChC,UAAU;AAAA,IACV;AAAA,IACA,MAAM,QAAQ;AAAA,IACd,SAAS,QAAQ;AAAA,EACnB;AACA,QAAM,oBAAoB,KAAK,UAAU,OAAO;AAChD,QAAM,kBAAkB,MAAM,YAAY,YAAQ,6BAAe,UAAU,GAAG,iBAAiB;AAC/F,MAAI,oBAAoB,GAAG;AACzB,UAAM,IAAI,+BAAiB,YAAY,4CAA4C;AAAA,EACrF;AAEA,QAAM,gBAAgB,mCAAY,IAAI,IAAI;AAE1C,YAAM,oBAAM,KAAK,IAAI,KAAK,cAAc,CAAC;AACzC,aAAS;AACP,UAAM,eAAe,MAAM,YAAY,aAAa,IAAI;AACxD,QAAI,cAAc;AAChB,aAAO;AAAA,IACT;AAGA,QAAK,MAAM,YAAY,OAAO,MAAM,MAAO,GAAG;AAC5C,YAAM,IAAI,+BAAiB,UAAU;AAAA,IACvC;AACA,QAAI,mCAAY,IAAI,KAAK,eAAe;AACtC,YAAM,IAAI,kCAAoB,cAAc;AAAA,IAC9C;AACA,cAAM,oBAAM,cAAc;AAAA,EAC5B;AACF;","names":[]}
|
|
@@ -55,6 +55,9 @@ async function redisRequest({
|
|
|
55
55
|
if (replyPayload) {
|
|
56
56
|
return replyPayload;
|
|
57
57
|
}
|
|
58
|
+
if (await redisClient.exists(aliveK) === 0) {
|
|
59
|
+
throw new NoResponderError(executorId);
|
|
60
|
+
}
|
|
58
61
|
if (performance.now() >= replyDeadline) {
|
|
59
62
|
throw new RequestTimeoutError(replyTimeoutMs);
|
|
60
63
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/request-reply/client.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\nimport { performance } from 'node:perf_hooks';\nimport type { RedisClientType } from 'redis';\nimport { NoResponderError, RequestTimeoutError } from './errors';\nimport type { JSONReply, JSONValue, PublishedRequest, RequestEnvelope } from './types';\nimport { jsonReplySchema } from './types';\nimport { heartbeatKey, replyKey, requestChannel, sleep } from './utils';\n\nexport interface SendRequestOptions {\n /** Max time to wait for a reply after the request is published (ms). */\n replyTimeoutMs: number;\n /** Sleep between poll attempts when the reply is not yet present (ms). */\n pollIntervalMs: number;\n}\n\nconst DEFAULT_REPLY_TIMEOUT_MS = 60_000;\nconst DEFAULT_POLL_INTERVAL_MS = 500;\n\nfunction resolveSendRequestOptions(options: Partial<SendRequestOptions> | undefined): SendRequestOptions {\n return {\n replyTimeoutMs: options?.replyTimeoutMs ?? DEFAULT_REPLY_TIMEOUT_MS,\n pollIntervalMs: options?.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS,\n };\n}\n\nfunction parseReplyPayload(raw: string) {\n const parsed: unknown = JSON.parse(raw);\n return jsonReplySchema.parse(parsed);\n}\n\nasync function getDelReply(redisClient: RedisClientType, rKey: string): Promise<JSONReply | null> {\n const raw = await redisClient.getDel(rKey);\n if (raw === null) {\n return null;\n }\n return parseReplyPayload(raw);\n}\n\n/**\n * Publishes the request (JSON) on the worker channel, then polls the reply key with GETDEL\n * (see https://redis.io/docs/latest/commands/getdel/ ) until a result arrives
|
|
1
|
+
{"version":3,"sources":["../../src/request-reply/client.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\nimport { performance } from 'node:perf_hooks';\nimport type { RedisClientType } from 'redis';\nimport { NoResponderError, RequestTimeoutError } from './errors';\nimport type { JSONReply, JSONValue, PublishedRequest, RequestEnvelope } from './types';\nimport { jsonReplySchema } from './types';\nimport { heartbeatKey, replyKey, requestChannel, sleep } from './utils';\n\nexport interface SendRequestOptions {\n /** Max time to wait for a reply after the request is published (ms). */\n replyTimeoutMs: number;\n /** Sleep between poll attempts when the reply is not yet present (ms). */\n pollIntervalMs: number;\n}\n\nconst DEFAULT_REPLY_TIMEOUT_MS = 60_000;\nconst DEFAULT_POLL_INTERVAL_MS = 500;\n\nfunction resolveSendRequestOptions(options: Partial<SendRequestOptions> | undefined): SendRequestOptions {\n return {\n replyTimeoutMs: options?.replyTimeoutMs ?? DEFAULT_REPLY_TIMEOUT_MS,\n pollIntervalMs: options?.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS,\n };\n}\n\nfunction parseReplyPayload(raw: string) {\n const parsed: unknown = JSON.parse(raw);\n return jsonReplySchema.parse(parsed);\n}\n\nasync function getDelReply(redisClient: RedisClientType, rKey: string): Promise<JSONReply | null> {\n const raw = await redisClient.getDel(rKey);\n if (raw === null) {\n return null;\n }\n return parseReplyPayload(raw);\n}\n\n/**\n * Publishes the request (JSON) on the worker channel, then polls the reply key with GETDEL\n * (see https://redis.io/docs/latest/commands/getdel/ ) until a result arrives, the executor\n * heartbeat expires, or the wait budget is exceeded.\n */\nexport async function redisRequest<T extends JSONValue>({\n redis: redisClient,\n executorId,\n path,\n request,\n options,\n}: {\n redis: RedisClientType;\n executorId: string;\n path: string;\n request: RequestEnvelope<T>;\n options?: Partial<SendRequestOptions> | undefined;\n}): Promise<JSONReply> {\n const { replyTimeoutMs, pollIntervalMs } = resolveSendRequestOptions(options);\n const aliveK = heartbeatKey(executorId);\n if ((await redisClient.exists(aliveK)) === 0) {\n throw new NoResponderError(executorId);\n }\n\n const requestId = randomUUID();\n const rKey = replyKey(requestId);\n const payload: PublishedRequest = {\n replyKey: rKey,\n path,\n body: request.body,\n headers: request.headers,\n };\n const serializedPayload = JSON.stringify(payload);\n const subscriberCount = await redisClient.publish(requestChannel(executorId), serializedPayload);\n if (subscriberCount === 0) {\n throw new NoResponderError(executorId, 'No executor received the published request');\n }\n\n const replyDeadline = performance.now() + replyTimeoutMs;\n // Give the executor a moment to process before the first poll.\n await sleep(Math.min(200, replyTimeoutMs));\n for (;;) {\n const replyPayload = await getDelReply(redisClient, rKey);\n if (replyPayload) {\n return replyPayload;\n }\n // We already checked that the executor was alive before sending, but it may have\n // died while we wait. Recheck here so we fail soon instead of waiting until the timeout.\n if ((await redisClient.exists(aliveK)) === 0) {\n throw new NoResponderError(executorId);\n }\n if (performance.now() >= replyDeadline) {\n throw new RequestTimeoutError(replyTime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EA,QAAM,gBAAgB,YAAY,IAAI,IAAI;AAE1C,QAAM,MAAM,KAAK,IAAI,KAAK,cAAc,CAAC;AACzC,aAAS;AACP,UAAM,eAAe,MAAM,YAAY,aAAa,IAAI;AACxD,QAAI,cAAc;AAChB,aAAO;AAAA,IACT;AAGA,QAAK,MAAM,YAAY,OAAO,MAAM,MAAO,GAAG;AAC5C,YAAM,IAAI,iBAAiB,UAAU;AAAA,IACvC;AACA,QAAI,YAAY,IAAI,KAAK,eAAe;AACtC,YAAM,IAAI,oBAAoB,cAAc;AAAA,IAC9C;AACA,UAAM,MAAM,cAAc;AAAA,EAC5B;AACF;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@truefoundry/trueforge-core",
|
|
3
|
-
"version": "0.2.0-rc.
|
|
3
|
+
"version": "0.2.0-rc.5",
|
|
4
4
|
"description": "TrueForge Agent Harness library.",
|
|
5
5
|
"author": "TrueFoundry",
|
|
6
6
|
"license": "MIT",
|
|
@@ -104,6 +104,7 @@
|
|
|
104
104
|
"dedent": "^1.7.2",
|
|
105
105
|
"openai": "^7.5.0",
|
|
106
106
|
"ulid": "^3.0.2",
|
|
107
|
+
"undici": "7.29.0",
|
|
107
108
|
"winston": "^3.19.0",
|
|
108
109
|
"ws": "^8.21.3",
|
|
109
110
|
"zod": "^4.4.3"
|