mcp-use 0.1.12 → 0.1.15
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/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -1
- package/dist/src/agents/index.d.ts +1 -0
- package/dist/src/agents/index.d.ts.map +1 -1
- package/dist/src/agents/index.js +1 -0
- package/dist/src/agents/mcp_agent.d.ts +7 -2
- package/dist/src/agents/mcp_agent.d.ts.map +1 -1
- package/dist/src/agents/mcp_agent.js +85 -10
- package/dist/src/agents/remote.d.ts +23 -0
- package/dist/src/agents/remote.d.ts.map +1 -0
- package/dist/src/agents/remote.js +264 -0
- package/package.json +3 -5
package/dist/index.d.ts
CHANGED
@@ -1,4 +1,5 @@
|
|
1
1
|
import { MCPAgent } from './src/agents/mcp_agent.js';
|
2
|
+
import { RemoteAgent } from './src/agents/remote.js';
|
2
3
|
import { MCPClient } from './src/client.js';
|
3
4
|
import { loadConfigFile } from './src/config.js';
|
4
5
|
import { BaseConnector } from './src/connectors/base.js';
|
@@ -14,5 +15,5 @@ export * from './src/managers/tools/index.js';
|
|
14
15
|
export { setTelemetrySource, Telemetry } from './src/telemetry/index.js';
|
15
16
|
export { AIMessage, BaseMessage, HumanMessage, SystemMessage, ToolMessage } from '@langchain/core/messages';
|
16
17
|
export type { StreamEvent } from '@langchain/core/tracers/log_stream';
|
17
|
-
export { BaseConnector, HttpConnector, loadConfigFile, Logger, logger, MCPAgent, MCPClient, MCPSession, StdioConnector, WebSocketConnector };
|
18
|
+
export { BaseConnector, HttpConnector, loadConfigFile, Logger, logger, MCPAgent, MCPClient, MCPSession, RemoteAgent, StdioConnector, WebSocketConnector };
|
18
19
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QA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,cAAc,EAAE,MAAM,iBAAiB,CAAA;AAChD,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAA;AACxD,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAA;AACxD,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAA;AAC1D,OAAO,EAAE,kBAAkB,EAAE,MAAM,+BAA+B,CAAA;AAElE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAA;AACjD,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAA;AAE7C,OAAO,EAAE,WAAW,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAA;AAEvE,cAAc,6BAA6B,CAAA;AAC3C,OAAO,EAAE,aAAa,EAAE,MAAM,kCAAkC,CAAA;AAEhE,cAAc,+BAA+B,CAAA;AAG7C,OAAO,EAAE,kBAAkB,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAA;AAGxE,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,YAAY,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAA;AAG3G,YAAY,EAAE,WAAW,EAAE,MAAM,oCAAoC,CAAA;AAErE,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,SAAS,EAAE,UAAU,EAAE,WAAW,EAAE,cAAc,EAAE,kBAAkB,EAAE,CAAA"}
|
package/dist/index.js
CHANGED
@@ -1,4 +1,5 @@
|
|
1
1
|
import { MCPAgent } from './src/agents/mcp_agent.js';
|
2
|
+
import { RemoteAgent } from './src/agents/remote.js';
|
2
3
|
import { MCPClient } from './src/client.js';
|
3
4
|
import { loadConfigFile } from './src/config.js';
|
4
5
|
import { BaseConnector } from './src/connectors/base.js';
|
@@ -16,4 +17,4 @@ export * from './src/managers/tools/index.js';
|
|
16
17
|
export { setTelemetrySource, Telemetry } from './src/telemetry/index.js';
|
17
18
|
// Re-export message classes to ensure a single constructor instance is shared by consumers
|
18
19
|
export { AIMessage, BaseMessage, HumanMessage, SystemMessage, ToolMessage } from '@langchain/core/messages';
|
19
|
-
export { BaseConnector, HttpConnector, loadConfigFile, Logger, logger, MCPAgent, MCPClient, MCPSession, StdioConnector, WebSocketConnector };
|
20
|
+
export { BaseConnector, HttpConnector, loadConfigFile, Logger, logger, MCPAgent, MCPClient, MCPSession, RemoteAgent, StdioConnector, WebSocketConnector };
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/agents/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAA;AACrC,OAAO,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAA"}
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/agents/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAA;AACrC,OAAO,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAA;AACzC,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAA"}
|
package/dist/src/agents/index.js
CHANGED
@@ -10,7 +10,7 @@ import { SystemMessage } from '@langchain/core/messages';
|
|
10
10
|
import { LangChainAdapter } from '../adapters/langchain_adapter.js';
|
11
11
|
import { ServerManager } from '../managers/server_manager.js';
|
12
12
|
export declare class MCPAgent {
|
13
|
-
private llm
|
13
|
+
private llm?;
|
14
14
|
private client?;
|
15
15
|
private connectors;
|
16
16
|
private maxSteps;
|
@@ -34,8 +34,10 @@ export declare class MCPAgent {
|
|
34
34
|
private telemetry;
|
35
35
|
private modelProvider;
|
36
36
|
private modelName;
|
37
|
+
private isRemote;
|
38
|
+
private remoteAgent;
|
37
39
|
constructor(options: {
|
38
|
-
llm
|
40
|
+
llm?: BaseLanguageModelInterface;
|
39
41
|
client?: MCPClient;
|
40
42
|
connectors?: BaseConnector[];
|
41
43
|
maxSteps?: number;
|
@@ -50,6 +52,9 @@ export declare class MCPAgent {
|
|
50
52
|
verbose?: boolean;
|
51
53
|
adapter?: LangChainAdapter;
|
52
54
|
serverManagerFactory?: (client: MCPClient) => ServerManager;
|
55
|
+
agentId?: string;
|
56
|
+
apiKey?: string;
|
57
|
+
baseUrl?: string;
|
53
58
|
});
|
54
59
|
initialize(): Promise<void>;
|
55
60
|
private createSystemMessageFromTools;
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"mcp_agent.d.ts","sourceRoot":"","sources":["../../../src/agents/mcp_agent.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,0BAA0B,EAAqB,MAAM,sCAAsC,CAAA;AACzG,OAAO,KAAK,EACV,WAAW,EACZ,MAAM,0BAA0B,CAAA;AACjC,OAAO,KAAK,EAAE,uBAAuB,EAAiB,MAAM,uBAAuB,CAAA;AACnF,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,oCAAoC,CAAA;AACrE,OAAO,KAAK,EAAe,SAAS,EAAE,MAAM,kBAAkB,CAAA;AAE9D,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,KAAK,CAAA;AACpC,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,cAAc,CAAA;AAC7C,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAA;AAE1D,OAAO,EAGL,aAAa,EAEd,MAAM,0BAA0B,CAAA;AAWjC,OAAO,EAAE,gBAAgB,EAAE,MAAM,kCAAkC,CAAA;AAEnE,OAAO,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAA;
|
1
|
+
{"version":3,"file":"mcp_agent.d.ts","sourceRoot":"","sources":["../../../src/agents/mcp_agent.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,0BAA0B,EAAqB,MAAM,sCAAsC,CAAA;AACzG,OAAO,KAAK,EACV,WAAW,EACZ,MAAM,0BAA0B,CAAA;AACjC,OAAO,KAAK,EAAE,uBAAuB,EAAiB,MAAM,uB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AE;YAIvB,iBAAiB;IAc/B;;OAEG;IACU,GAAG,CACd,KAAK,EAAE,MAAM,EACb,QAAQ,CAAC,EAAE,MAAM,EACjB,eAAe,CAAC,EAAE,OAAO,EACzB,eAAe,CAAC,EAAE,WAAW,EAAE,GAC9B,OAAO,CAAC,MAAM,CAAC;IAElB;;OAEG;IACU,GAAG,CAAC,CAAC,EAChB,KAAK,EAAE,MAAM,EACb,QAAQ,CAAC,EAAE,MAAM,EACjB,eAAe,CAAC,EAAE,OAAO,EACzB,eAAe,CAAC,EAAE,WAAW,EAAE,EAC/B,YAAY,CAAC,EAAE,SAAS,CAAC,CAAC,CAAC,GAC1B,OAAO,CAAC,CAAC,CAAC;IAwBb;;;OAGG;IACW,MAAM,CAAC,CAAC,GAAG,MAAM,EAC7B,KAAK,EAAE,MAAM,EACb,QAAQ,CAAC,EAAE,MAAM,EACjB,eAAe,UAAO,EACtB,eAAe,CAAC,EAAE,WAAW,EAAE,EAC/B,YAAY,CAAC,EAAE,SAAS,CAAC,CAAC,CAAC,GAC1B,cAAc,CAAC,SAAS,EAAE,MAAM,GAAG,CAAC,EAAE,IAAI,CAAC;IAoRjC,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAgCnC;;;OAGG;IACW,YAAY,CACxB,KAAK,EAAE,MAAM,EACb,QAAQ,CAAC,EAAE,MAAM,EACjB,eAAe,UAAO,EACtB,eAAe,CAAC,EAAE,WAAW,EAAE,GAC9B,cAAc,CAAC,WAAW,EAAE,IAAI,EAAE,IAAI,CAAC;IAgJ1C;;OAEG;YACW,wBAAwB;IAqFtC;;OAEG;IACH,OAAO,CAAC,yBAAyB;IAgCjC;;OAEG;IACH,OAAO,CAAC,uBAAuB;CAuBhC"}
|
@@ -9,6 +9,7 @@ import { ServerManager } from '../managers/server_manager.js';
|
|
9
9
|
import { extractModelInfo, Telemetry } from '../telemetry/index.js';
|
10
10
|
import { createSystemMessage } from './prompts/system_prompt_builder.js';
|
11
11
|
import { DEFAULT_SYSTEM_PROMPT_TEMPLATE, SERVER_MANAGER_SYSTEM_PROMPT_TEMPLATE } from './prompts/templates.js';
|
12
|
+
import { RemoteAgent } from './remote.js';
|
12
13
|
export class MCPAgent {
|
13
14
|
llm;
|
14
15
|
client;
|
@@ -34,7 +35,37 @@ export class MCPAgent {
|
|
34
35
|
telemetry;
|
35
36
|
modelProvider;
|
36
37
|
modelName;
|
38
|
+
// Remote agent support
|
39
|
+
isRemote = false;
|
40
|
+
remoteAgent = null;
|
37
41
|
constructor(options) {
|
42
|
+
// Handle remote execution
|
43
|
+
if (options.agentId) {
|
44
|
+
this.isRemote = true;
|
45
|
+
this.remoteAgent = new RemoteAgent({
|
46
|
+
agentId: options.agentId,
|
47
|
+
apiKey: options.apiKey,
|
48
|
+
baseUrl: options.baseUrl,
|
49
|
+
});
|
50
|
+
// Set default values for remote agent
|
51
|
+
this.maxSteps = options.maxSteps ?? 5;
|
52
|
+
this.memoryEnabled = options.memoryEnabled ?? true;
|
53
|
+
this.autoInitialize = options.autoInitialize ?? false;
|
54
|
+
this.verbose = options.verbose ?? false;
|
55
|
+
this.connectors = [];
|
56
|
+
this.disallowedTools = [];
|
57
|
+
this.additionalTools = [];
|
58
|
+
this.useServerManager = false;
|
59
|
+
this.adapter = new LangChainAdapter();
|
60
|
+
this.telemetry = Telemetry.getInstance();
|
61
|
+
this.modelProvider = 'remote';
|
62
|
+
this.modelName = 'remote-agent';
|
63
|
+
return;
|
64
|
+
}
|
65
|
+
// Validate requirements for local execution
|
66
|
+
if (!options.llm) {
|
67
|
+
throw new Error('llm is required for local execution. For remote execution, provide agentId instead.');
|
68
|
+
}
|
38
69
|
this.llm = options.llm;
|
39
70
|
this.client = options.client;
|
40
71
|
this.connectors = options.connectors ?? [];
|
@@ -65,9 +96,15 @@ export class MCPAgent {
|
|
65
96
|
// Initialize telemetry
|
66
97
|
this.telemetry = Telemetry.getInstance();
|
67
98
|
// Track model info for telemetry
|
68
|
-
|
69
|
-
|
70
|
-
|
99
|
+
if (this.llm) {
|
100
|
+
const [provider, name] = extractModelInfo(this.llm);
|
101
|
+
this.modelProvider = provider;
|
102
|
+
this.modelName = name;
|
103
|
+
}
|
104
|
+
else {
|
105
|
+
this.modelProvider = 'unknown';
|
106
|
+
this.modelName = 'unknown';
|
107
|
+
}
|
71
108
|
// Make getters configurable for test mocking
|
72
109
|
Object.defineProperty(this, 'agentExecutor', {
|
73
110
|
get: () => this._agentExecutor,
|
@@ -83,6 +120,11 @@ export class MCPAgent {
|
|
83
120
|
});
|
84
121
|
}
|
85
122
|
async initialize() {
|
123
|
+
// Skip initialization for remote agents
|
124
|
+
if (this.isRemote) {
|
125
|
+
this._initialized = true;
|
126
|
+
return;
|
127
|
+
}
|
86
128
|
logger.info('🚀 Initializing MCP agent and connecting to services...');
|
87
129
|
// If using server manager, initialize it
|
88
130
|
if (this.useServerManager && this.serverManager) {
|
@@ -147,6 +189,9 @@ export class MCPAgent {
|
|
147
189
|
}
|
148
190
|
}
|
149
191
|
createAgent() {
|
192
|
+
if (!this.llm) {
|
193
|
+
throw new Error('LLM is required to create agent');
|
194
|
+
}
|
150
195
|
const systemContent = this.systemMessage?.content ?? 'You are a helpful assistant.';
|
151
196
|
const prompt = ChatPromptTemplate.fromMessages([
|
152
197
|
['system', systemContent],
|
@@ -213,6 +258,10 @@ export class MCPAgent {
|
|
213
258
|
}
|
214
259
|
}
|
215
260
|
async run(query, maxSteps, manageConnector, externalHistory, outputSchema) {
|
261
|
+
// Delegate to remote agent if in remote mode
|
262
|
+
if (this.isRemote && this.remoteAgent) {
|
263
|
+
return this.remoteAgent.run(query, maxSteps, manageConnector, externalHistory, outputSchema);
|
264
|
+
}
|
216
265
|
const generator = this.stream(query, maxSteps, manageConnector, externalHistory, outputSchema);
|
217
266
|
return this._consumeAndReturn(generator);
|
218
267
|
}
|
@@ -221,6 +270,11 @@ export class MCPAgent {
|
|
221
270
|
* If outputSchema is provided, returns structured output of type T.
|
222
271
|
*/
|
223
272
|
async *stream(query, maxSteps, manageConnector = true, externalHistory, outputSchema) {
|
273
|
+
// Delegate to remote agent if in remote mode
|
274
|
+
if (this.isRemote && this.remoteAgent) {
|
275
|
+
const result = await this.remoteAgent.run(query, maxSteps, manageConnector, externalHistory, outputSchema);
|
276
|
+
return result;
|
277
|
+
}
|
224
278
|
let result = '';
|
225
279
|
let initializedHere = false;
|
226
280
|
const startTime = Date.now();
|
@@ -234,13 +288,16 @@ export class MCPAgent {
|
|
234
288
|
query = this._enhanceQueryWithSchema(query, outputSchema);
|
235
289
|
logger.debug(`🔄 Structured output requested, schema: ${JSON.stringify(zodToJsonSchema(outputSchema), null, 2)}`);
|
236
290
|
// Check if withStructuredOutput method exists
|
237
|
-
if ('withStructuredOutput' in this.llm && typeof this.llm.withStructuredOutput === 'function') {
|
291
|
+
if (this.llm && 'withStructuredOutput' in this.llm && typeof this.llm.withStructuredOutput === 'function') {
|
238
292
|
structuredLlm = this.llm.withStructuredOutput(outputSchema);
|
239
293
|
}
|
240
|
-
else {
|
294
|
+
else if (this.llm) {
|
241
295
|
// Fallback: use the same LLM but we'll handle structure in our helper method
|
242
296
|
structuredLlm = this.llm;
|
243
297
|
}
|
298
|
+
else {
|
299
|
+
throw new Error('LLM is required for structured output');
|
300
|
+
}
|
244
301
|
schemaDescription = JSON.stringify(zodToJsonSchema(outputSchema), null, 2);
|
245
302
|
}
|
246
303
|
try {
|
@@ -444,6 +501,11 @@ export class MCPAgent {
|
|
444
501
|
}
|
445
502
|
}
|
446
503
|
async close() {
|
504
|
+
// Delegate to remote agent if in remote mode
|
505
|
+
if (this.isRemote && this.remoteAgent) {
|
506
|
+
await this.remoteAgent.close();
|
507
|
+
return;
|
508
|
+
}
|
447
509
|
logger.info('🔌 Closing MCPAgent resources…');
|
448
510
|
try {
|
449
511
|
this._agentExecutor = null;
|
@@ -596,9 +658,22 @@ export class MCPAgent {
|
|
596
658
|
* Attempt to create structured output from raw result with validation and retry logic.
|
597
659
|
*/
|
598
660
|
async _attemptStructuredOutput(rawResult, structuredLlm, outputSchema, schemaDescription) {
|
599
|
-
logger.
|
600
|
-
logger.
|
601
|
-
logger.
|
661
|
+
logger.info(`🔄 Attempting structured output with schema: ${outputSchema}`);
|
662
|
+
logger.info(`🔄 Schema description: ${schemaDescription}`);
|
663
|
+
logger.info(`🔄 Raw result: ${JSON.stringify(rawResult, null, 2)}`);
|
664
|
+
// Handle different input formats - rawResult might be an array or object from the agent
|
665
|
+
let textContent = '';
|
666
|
+
if (typeof rawResult === 'string') {
|
667
|
+
textContent = rawResult;
|
668
|
+
}
|
669
|
+
else if (rawResult && typeof rawResult === 'object') {
|
670
|
+
// Handle object format
|
671
|
+
textContent = JSON.stringify(rawResult);
|
672
|
+
}
|
673
|
+
// If we couldn't extract text, use the stringified version
|
674
|
+
if (!textContent) {
|
675
|
+
textContent = JSON.stringify(rawResult);
|
676
|
+
}
|
602
677
|
// Get detailed schema information for better prompting
|
603
678
|
const maxRetries = 3;
|
604
679
|
let lastError = '';
|
@@ -611,8 +686,8 @@ export class MCPAgent {
|
|
611
686
|
Required schema format:
|
612
687
|
${schemaDescription}
|
613
688
|
|
614
|
-
Content to
|
615
|
-
${
|
689
|
+
Content to extract from:
|
690
|
+
${textContent}
|
616
691
|
|
617
692
|
IMPORTANT:
|
618
693
|
- Use ONLY the field names specified in the schema
|
@@ -0,0 +1,23 @@
|
|
1
|
+
/**
|
2
|
+
* Remote agent implementation for executing agents via API.
|
3
|
+
*/
|
4
|
+
import type { BaseMessage } from '@langchain/core/messages';
|
5
|
+
import type { ZodSchema } from 'zod';
|
6
|
+
export declare class RemoteAgent {
|
7
|
+
private agentId;
|
8
|
+
private apiKey;
|
9
|
+
private baseUrl;
|
10
|
+
private chatId;
|
11
|
+
constructor(options: {
|
12
|
+
agentId: string;
|
13
|
+
apiKey?: string;
|
14
|
+
baseUrl?: string;
|
15
|
+
});
|
16
|
+
private pydanticToJsonSchema;
|
17
|
+
private parseStructuredResponse;
|
18
|
+
private createChatSession;
|
19
|
+
run<T = string>(query: string, maxSteps?: number, manageConnector?: boolean, externalHistory?: BaseMessage[], outputSchema?: ZodSchema<T>): Promise<T>;
|
20
|
+
stream<T = string>(query: string, maxSteps?: number, manageConnector?: boolean, externalHistory?: BaseMessage[], outputSchema?: ZodSchema<T>): AsyncGenerator<any, T, void>;
|
21
|
+
close(): Promise<void>;
|
22
|
+
}
|
23
|
+
//# sourceMappingURL=remote.d.ts.map
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"file":"remote.d.ts","sourceRoot":"","sources":["../../../src/agents/remote.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAA;AAC3D,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,KAAK,CAAA;AAQpC,qBAAa,WAAW;IACtB,OAAO,CAAC,OAAO,CAAQ;IACvB,OAAO,CAAC,MAAM,CAAQ;IACtB,OAAO,CAAC,OAAO,CAAQ;IACvB,OAAO,CAAC,MAAM,CAAsB;gBAExB,OAAO,EAAE;QACnB,OAAO,EAAE,MAAM,CAAA;QACf,MAAM,CAAC,EAAE,MAAM,CAAA;QACf,OAAO,CAAC,EAAE,MAAM,CAAA;KACjB;IAgBD,OAAO,CAAC,oBAAoB;IAO5B,OAAO,CAAC,uBAAuB;YAoDjB,iBAAiB;IAmDlB,GAAG,CAAC,CAAC,GAAG,MAAM,EACzB,KAAK,EAAE,MAAM,EACb,QAAQ,CAAC,EAAE,MAAM,EACjB,eAAe,CAAC,EAAE,OAAO,EACzB,eAAe,CAAC,EAAE,WAAW,EAAE,EAC/B,YAAY,CAAC,EAAE,SAAS,CAAC,CAAC,CAAC,GAC1B,OAAO,CAAC,CAAC,CAAC;IAwJC,MAAM,CAAC,CAAC,GAAG,MAAM,EAC7B,KAAK,EAAE,MAAM,EACb,QAAQ,CAAC,EAAE,MAAM,EACjB,eAAe,CAAC,EAAE,OAAO,EACzB,eAAe,CAAC,EAAE,WAAW,EAAE,EAC/B,YAAY,CAAC,EAAE,SAAS,CAAC,CAAC,CAAC,GAC1B,cAAc,CAAC,GAAG,EAAE,CAAC,EAAE,IAAI,CAAC;IASlB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;CAUpC"}
|
@@ -0,0 +1,264 @@
|
|
1
|
+
/**
|
2
|
+
* Remote agent implementation for executing agents via API.
|
3
|
+
*/
|
4
|
+
import { zodToJsonSchema } from 'zod-to-json-schema';
|
5
|
+
import { logger } from '../logging.js';
|
6
|
+
// API endpoint constants
|
7
|
+
const API_CHATS_ENDPOINT = '/api/v1/chats';
|
8
|
+
const API_CHAT_EXECUTE_ENDPOINT = '/api/v1/chats/{chat_id}/execute';
|
9
|
+
export class RemoteAgent {
|
10
|
+
agentId;
|
11
|
+
apiKey;
|
12
|
+
baseUrl;
|
13
|
+
chatId = null;
|
14
|
+
constructor(options) {
|
15
|
+
this.agentId = options.agentId;
|
16
|
+
this.baseUrl = options.baseUrl ?? 'https://cloud.mcp-use.com';
|
17
|
+
// Handle API key validation
|
18
|
+
const apiKey = options.apiKey ?? process.env.MCP_USE_API_KEY;
|
19
|
+
if (!apiKey) {
|
20
|
+
throw new Error('API key is required for remote execution. '
|
21
|
+
+ 'Please provide it as a parameter or set the MCP_USE_API_KEY environment variable. '
|
22
|
+
+ 'You can get an API key from https://cloud.mcp-use.com');
|
23
|
+
}
|
24
|
+
this.apiKey = apiKey;
|
25
|
+
}
|
26
|
+
pydanticToJsonSchema(schema) {
|
27
|
+
/**
|
28
|
+
* Convert a Zod schema to JSON schema for API transmission.
|
29
|
+
*/
|
30
|
+
return zodToJsonSchema(schema);
|
31
|
+
}
|
32
|
+
parseStructuredResponse(responseData, outputSchema) {
|
33
|
+
/**
|
34
|
+
* Parse the API response into the structured output format.
|
35
|
+
*/
|
36
|
+
let resultData;
|
37
|
+
// Handle different response formats
|
38
|
+
if (typeof responseData === 'object' && responseData !== null) {
|
39
|
+
if ('result' in responseData) {
|
40
|
+
const outerResult = responseData.result;
|
41
|
+
// Check if this is a nested result structure (agent execution response)
|
42
|
+
if (typeof outerResult === 'object' && outerResult !== null && 'result' in outerResult) {
|
43
|
+
// Extract the actual structured output from the nested result
|
44
|
+
resultData = outerResult.result;
|
45
|
+
}
|
46
|
+
else {
|
47
|
+
// Use the outer result directly
|
48
|
+
resultData = outerResult;
|
49
|
+
}
|
50
|
+
}
|
51
|
+
else {
|
52
|
+
resultData = responseData;
|
53
|
+
}
|
54
|
+
}
|
55
|
+
else if (typeof responseData === 'string') {
|
56
|
+
try {
|
57
|
+
resultData = JSON.parse(responseData);
|
58
|
+
}
|
59
|
+
catch {
|
60
|
+
// If it's not valid JSON, try to create the model from the string content
|
61
|
+
resultData = { content: responseData };
|
62
|
+
}
|
63
|
+
}
|
64
|
+
else {
|
65
|
+
resultData = responseData;
|
66
|
+
}
|
67
|
+
// Parse into the Zod schema
|
68
|
+
try {
|
69
|
+
return outputSchema.parse(resultData);
|
70
|
+
}
|
71
|
+
catch (e) {
|
72
|
+
logger.warn(`Failed to parse structured output: ${e}`);
|
73
|
+
// Fallback: try to parse it as raw content if the schema has a content field
|
74
|
+
const schemaShape = outputSchema._def?.shape();
|
75
|
+
if (schemaShape && 'content' in schemaShape) {
|
76
|
+
return outputSchema.parse({ content: String(resultData) });
|
77
|
+
}
|
78
|
+
throw e;
|
79
|
+
}
|
80
|
+
}
|
81
|
+
async createChatSession() {
|
82
|
+
/**
|
83
|
+
* Create a persistent chat session for the agent.
|
84
|
+
*/
|
85
|
+
const chatPayload = {
|
86
|
+
title: `Remote Agent Session - ${this.agentId}`,
|
87
|
+
agent_id: this.agentId,
|
88
|
+
type: 'agent_execution',
|
89
|
+
};
|
90
|
+
const headers = {
|
91
|
+
'Content-Type': 'application/json',
|
92
|
+
'x-api-key': this.apiKey,
|
93
|
+
};
|
94
|
+
const chatUrl = `${this.baseUrl}${API_CHATS_ENDPOINT}`;
|
95
|
+
logger.info(`📝 Creating chat session for agent ${this.agentId}`);
|
96
|
+
try {
|
97
|
+
const response = await fetch(chatUrl, {
|
98
|
+
method: 'POST',
|
99
|
+
headers,
|
100
|
+
body: JSON.stringify(chatPayload),
|
101
|
+
});
|
102
|
+
if (!response.ok) {
|
103
|
+
const responseText = await response.text();
|
104
|
+
const statusCode = response.status;
|
105
|
+
if (statusCode === 404) {
|
106
|
+
throw new Error(`Agent not found: Agent '${this.agentId}' does not exist or you don't have access to it. `
|
107
|
+
+ 'Please verify the agent ID and ensure it exists in your account.');
|
108
|
+
}
|
109
|
+
throw new Error(`Failed to create chat session: ${statusCode} - ${responseText}`);
|
110
|
+
}
|
111
|
+
const chatData = await response.json();
|
112
|
+
const chatId = chatData.id;
|
113
|
+
logger.info(`✅ Chat session created: ${chatId}`);
|
114
|
+
return chatId;
|
115
|
+
}
|
116
|
+
catch (e) {
|
117
|
+
if (e instanceof Error) {
|
118
|
+
throw new TypeError(`Failed to create chat session: ${e.message}`);
|
119
|
+
}
|
120
|
+
throw new Error(`Failed to create chat session: ${String(e)}`);
|
121
|
+
}
|
122
|
+
}
|
123
|
+
async run(query, maxSteps, manageConnector, externalHistory, outputSchema) {
|
124
|
+
/**
|
125
|
+
* Run a query on the remote agent.
|
126
|
+
*/
|
127
|
+
if (externalHistory !== undefined) {
|
128
|
+
logger.warn('External history is not yet supported for remote execution');
|
129
|
+
}
|
130
|
+
try {
|
131
|
+
logger.info(`🌐 Executing query on remote agent ${this.agentId}`);
|
132
|
+
// Step 1: Create a chat session for this agent (only if we don't have one)
|
133
|
+
if (this.chatId === null) {
|
134
|
+
this.chatId = await this.createChatSession();
|
135
|
+
}
|
136
|
+
const chatId = this.chatId;
|
137
|
+
// Step 2: Execute the agent within the chat context
|
138
|
+
const executionPayload = {
|
139
|
+
query,
|
140
|
+
max_steps: maxSteps ?? 10,
|
141
|
+
};
|
142
|
+
// Add structured output schema if provided
|
143
|
+
if (outputSchema) {
|
144
|
+
executionPayload.output_schema = this.pydanticToJsonSchema(outputSchema);
|
145
|
+
logger.info(`🔧 Using structured output with schema`);
|
146
|
+
}
|
147
|
+
const headers = {
|
148
|
+
'Content-Type': 'application/json',
|
149
|
+
'x-api-key': this.apiKey,
|
150
|
+
};
|
151
|
+
const executionUrl = `${this.baseUrl}${API_CHAT_EXECUTE_ENDPOINT.replace('{chat_id}', chatId)}`;
|
152
|
+
logger.info(`🚀 Executing agent in chat ${chatId}`);
|
153
|
+
const response = await fetch(executionUrl, {
|
154
|
+
method: 'POST',
|
155
|
+
headers,
|
156
|
+
body: JSON.stringify(executionPayload),
|
157
|
+
signal: AbortSignal.timeout(300000), // 5 minute timeout
|
158
|
+
});
|
159
|
+
if (!response.ok) {
|
160
|
+
const responseText = await response.text();
|
161
|
+
const statusCode = response.status;
|
162
|
+
// Provide specific error messages based on status code
|
163
|
+
if (statusCode === 401) {
|
164
|
+
logger.error(`❌ Authentication failed: ${responseText}`);
|
165
|
+
throw new Error('Authentication failed: Invalid or missing API key. '
|
166
|
+
+ 'Please check your API key and ensure the MCP_USE_API_KEY environment variable is set correctly.');
|
167
|
+
}
|
168
|
+
else if (statusCode === 403) {
|
169
|
+
logger.error(`❌ Access forbidden: ${responseText}`);
|
170
|
+
throw new Error(`Access denied: You don't have permission to execute agent '${this.agentId}'. `
|
171
|
+
+ 'Check if the agent exists and you have the necessary permissions.');
|
172
|
+
}
|
173
|
+
else if (statusCode === 404) {
|
174
|
+
logger.error(`❌ Agent not found: ${responseText}`);
|
175
|
+
throw new Error(`Agent not found: Agent '${this.agentId}' does not exist or you don't have access to it. `
|
176
|
+
+ 'Please verify the agent ID and ensure it exists in your account.');
|
177
|
+
}
|
178
|
+
else if (statusCode === 422) {
|
179
|
+
logger.error(`❌ Validation error: ${responseText}`);
|
180
|
+
throw new Error(`Request validation failed: ${responseText}. `
|
181
|
+
+ 'Please check your query parameters and output schema format.');
|
182
|
+
}
|
183
|
+
else if (statusCode === 500) {
|
184
|
+
logger.error(`❌ Server error: ${responseText}`);
|
185
|
+
throw new Error('Internal server error occurred during agent execution. '
|
186
|
+
+ 'Please try again later or contact support if the issue persists.');
|
187
|
+
}
|
188
|
+
else {
|
189
|
+
logger.error(`❌ Remote execution failed with status ${statusCode}: ${responseText}`);
|
190
|
+
throw new Error(`Remote agent execution failed: ${statusCode} - ${responseText}`);
|
191
|
+
}
|
192
|
+
}
|
193
|
+
const result = await response.json();
|
194
|
+
logger.info(`🔧 Response: ${JSON.stringify(result)}`);
|
195
|
+
logger.info('✅ Remote execution completed successfully');
|
196
|
+
// Check for error responses (even with 200 status)
|
197
|
+
if (typeof result === 'object' && result !== null) {
|
198
|
+
// Check for actual error conditions (not just presence of error field)
|
199
|
+
if (result.status === 'error' || result.error !== null) {
|
200
|
+
const errorMsg = result.error ?? String(result);
|
201
|
+
logger.error(`❌ Remote agent execution failed: ${errorMsg}`);
|
202
|
+
throw new Error(`Remote agent execution failed: ${errorMsg}`);
|
203
|
+
}
|
204
|
+
// Check if the response indicates agent initialization failure
|
205
|
+
if (String(result).includes('failed to initialize')) {
|
206
|
+
logger.error(`❌ Agent initialization failed: ${result}`);
|
207
|
+
throw new Error('Agent initialization failed on remote server. '
|
208
|
+
+ 'This usually indicates:\n'
|
209
|
+
+ '• Invalid agent configuration (LLM model, system prompt)\n'
|
210
|
+
+ '• Missing or invalid MCP server configurations\n'
|
211
|
+
+ '• Network connectivity issues with MCP servers\n'
|
212
|
+
+ '• Missing environment variables or credentials\n'
|
213
|
+
+ `Raw error: ${result}`);
|
214
|
+
}
|
215
|
+
}
|
216
|
+
// Handle structured output
|
217
|
+
if (outputSchema) {
|
218
|
+
return this.parseStructuredResponse(result, outputSchema);
|
219
|
+
}
|
220
|
+
// Regular string output
|
221
|
+
if (typeof result === 'object' && result !== null && 'result' in result) {
|
222
|
+
return result.result;
|
223
|
+
}
|
224
|
+
else if (typeof result === 'string') {
|
225
|
+
return result;
|
226
|
+
}
|
227
|
+
else {
|
228
|
+
return String(result);
|
229
|
+
}
|
230
|
+
}
|
231
|
+
catch (e) {
|
232
|
+
if (e instanceof Error) {
|
233
|
+
// Check for specific error types
|
234
|
+
if (e.name === 'AbortError') {
|
235
|
+
logger.error(`❌ Remote execution timed out: ${e}`);
|
236
|
+
throw new Error('Remote agent execution timed out. The server may be overloaded or the query is taking too long to '
|
237
|
+
+ 'process. Try again or use a simpler query.');
|
238
|
+
}
|
239
|
+
logger.error(`❌ Remote execution error: ${e}`);
|
240
|
+
throw new Error(`Remote agent execution failed: ${e.message}`);
|
241
|
+
}
|
242
|
+
logger.error(`❌ Remote execution error: ${e}`);
|
243
|
+
throw new Error(`Remote agent execution failed: ${String(e)}`);
|
244
|
+
}
|
245
|
+
}
|
246
|
+
async *stream(query, maxSteps, manageConnector, externalHistory, outputSchema) {
|
247
|
+
/**
|
248
|
+
* Stream implementation for remote agent - currently just wraps run.
|
249
|
+
* In the future, this could be enhanced to support actual streaming from the API.
|
250
|
+
*/
|
251
|
+
const result = await this.run(query, maxSteps, manageConnector, externalHistory, outputSchema);
|
252
|
+
return result;
|
253
|
+
}
|
254
|
+
async close() {
|
255
|
+
/**
|
256
|
+
* Close the remote agent connection.
|
257
|
+
*/
|
258
|
+
logger.info('🔌 Remote agent client closed');
|
259
|
+
// In the future, we might want to delete the chat session here
|
260
|
+
// if (this.chatId) {
|
261
|
+
// await this.deleteChatSession(this.chatId)
|
262
|
+
// }
|
263
|
+
}
|
264
|
+
}
|
package/package.json
CHANGED
@@ -1,7 +1,7 @@
|
|
1
1
|
{
|
2
2
|
"name": "mcp-use",
|
3
3
|
"type": "module",
|
4
|
-
"version": "0.1.
|
4
|
+
"version": "0.1.15",
|
5
5
|
"packageManager": "pnpm@10.6.1",
|
6
6
|
"description": "A utility library for integrating Model Context Protocol (MCP) with LangChain, Zod, and related tools. Provides helpers for schema conversion, event streaming, and SDK usage.",
|
7
7
|
"author": "Zane",
|
@@ -111,10 +111,8 @@
|
|
111
111
|
},
|
112
112
|
"lint-staged": {
|
113
113
|
"*.{js,ts}": [
|
114
|
-
"
|
115
|
-
|
116
|
-
"**/*.ts": [
|
117
|
-
"npm run build"
|
114
|
+
"eslint --fix",
|
115
|
+
"eslint"
|
118
116
|
]
|
119
117
|
}
|
120
118
|
}
|