agents 0.0.0-86dfe61 → 0.0.0-881f11e
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/ai-chat-agent.d.ts +22 -2
- package/dist/ai-chat-agent.js +92 -26
- package/dist/ai-chat-agent.js.map +1 -1
- package/dist/ai-react.d.ts +1 -0
- package/dist/ai-react.js +25 -16
- package/dist/ai-react.js.map +1 -1
- package/dist/ai-types.d.ts +5 -0
- package/dist/chunk-7VFQNJFK.js +462 -0
- package/dist/chunk-7VFQNJFK.js.map +1 -0
- package/dist/{chunk-XG52S6YY.js → chunk-JR3NW4A7.js} +79 -49
- package/dist/chunk-JR3NW4A7.js.map +1 -0
- package/dist/index.d.ts +25 -9
- package/dist/index.js +6 -5
- package/dist/mcp/client.d.ts +102 -31
- package/dist/mcp/client.js +4 -465
- package/dist/mcp/client.js.map +1 -1
- package/dist/mcp/do-oauth-client-provider.d.ts +41 -0
- package/dist/mcp/do-oauth-client-provider.js +107 -0
- package/dist/mcp/do-oauth-client-provider.js.map +1 -0
- package/dist/mcp/index.d.ts +34 -4
- package/dist/mcp/index.js +571 -104
- package/dist/mcp/index.js.map +1 -1
- package/package.json +25 -5
- package/src/index.ts +56 -12
- package/dist/chunk-XG52S6YY.js.map +0 -1
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
import {
|
|
2
|
+
MCPClientManager
|
|
3
|
+
} from "./chunk-7VFQNJFK.js";
|
|
1
4
|
import {
|
|
2
5
|
__privateAdd,
|
|
3
6
|
__privateGet,
|
|
@@ -36,18 +39,74 @@ function getNextCronTime(cron) {
|
|
|
36
39
|
var STATE_ROW_ID = "cf_state_row_id";
|
|
37
40
|
var STATE_WAS_CHANGED = "cf_state_was_changed";
|
|
38
41
|
var DEFAULT_STATE = {};
|
|
39
|
-
var
|
|
40
|
-
|
|
42
|
+
var agentContext = new AsyncLocalStorage();
|
|
43
|
+
function getCurrentAgent() {
|
|
44
|
+
const store = agentContext.getStore();
|
|
45
|
+
if (!store) {
|
|
46
|
+
return {
|
|
47
|
+
agent: void 0,
|
|
48
|
+
connection: void 0,
|
|
49
|
+
request: void 0
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
return store;
|
|
53
|
+
}
|
|
54
|
+
var _state, _ParentClass, _Agent_instances, setStateInternal_fn, tryCatch_fn, scheduleNextAlarm_fn, isCallable_fn;
|
|
41
55
|
var Agent = class extends Server {
|
|
42
56
|
constructor(ctx, env) {
|
|
43
57
|
super(ctx, env);
|
|
44
58
|
__privateAdd(this, _Agent_instances);
|
|
45
59
|
__privateAdd(this, _state, DEFAULT_STATE);
|
|
60
|
+
__privateAdd(this, _ParentClass, Object.getPrototypeOf(this).constructor);
|
|
61
|
+
this.mcp = new MCPClientManager(__privateGet(this, _ParentClass).name, "0.0.1");
|
|
46
62
|
/**
|
|
47
63
|
* Initial state for the Agent
|
|
48
64
|
* Override to provide default state values
|
|
49
65
|
*/
|
|
50
66
|
this.initialState = DEFAULT_STATE;
|
|
67
|
+
/**
|
|
68
|
+
* Method called when an alarm fires.
|
|
69
|
+
* Executes any scheduled tasks that are due.
|
|
70
|
+
*
|
|
71
|
+
* @remarks
|
|
72
|
+
* To schedule a task, please use the `this.schedule` method instead.
|
|
73
|
+
* See {@link https://developers.cloudflare.com/agents/api-reference/schedule-tasks/}
|
|
74
|
+
*/
|
|
75
|
+
this.alarm = async () => {
|
|
76
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
77
|
+
const result = this.sql`
|
|
78
|
+
SELECT * FROM cf_agents_schedules WHERE time <= ${now}
|
|
79
|
+
`;
|
|
80
|
+
for (const row of result || []) {
|
|
81
|
+
const callback = this[row.callback];
|
|
82
|
+
if (!callback) {
|
|
83
|
+
console.error(`callback ${row.callback} not found`);
|
|
84
|
+
continue;
|
|
85
|
+
}
|
|
86
|
+
await agentContext.run(
|
|
87
|
+
{ agent: this, connection: void 0, request: void 0 },
|
|
88
|
+
async () => {
|
|
89
|
+
try {
|
|
90
|
+
await callback.bind(this)(JSON.parse(row.payload), row);
|
|
91
|
+
} catch (e) {
|
|
92
|
+
console.error(`error executing callback "${row.callback}"`, e);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
);
|
|
96
|
+
if (row.type === "cron") {
|
|
97
|
+
const nextExecutionTime = getNextCronTime(row.cron);
|
|
98
|
+
const nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1e3);
|
|
99
|
+
this.sql`
|
|
100
|
+
UPDATE cf_agents_schedules SET time = ${nextTimestamp} WHERE id = ${row.id}
|
|
101
|
+
`;
|
|
102
|
+
} else {
|
|
103
|
+
this.sql`
|
|
104
|
+
DELETE FROM cf_agents_schedules WHERE id = ${row.id}
|
|
105
|
+
`;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
await __privateMethod(this, _Agent_instances, scheduleNextAlarm_fn).call(this);
|
|
109
|
+
};
|
|
51
110
|
this.sql`
|
|
52
111
|
CREATE TABLE IF NOT EXISTS cf_agents_state (
|
|
53
112
|
id TEXT PRIMARY KEY NOT NULL,
|
|
@@ -71,9 +130,18 @@ var Agent = class extends Server {
|
|
|
71
130
|
await this.alarm();
|
|
72
131
|
});
|
|
73
132
|
});
|
|
133
|
+
const _onRequest = this.onRequest.bind(this);
|
|
134
|
+
this.onRequest = (request) => {
|
|
135
|
+
return agentContext.run(
|
|
136
|
+
{ agent: this, connection: void 0, request },
|
|
137
|
+
async () => {
|
|
138
|
+
return __privateMethod(this, _Agent_instances, tryCatch_fn).call(this, () => _onRequest(request));
|
|
139
|
+
}
|
|
140
|
+
);
|
|
141
|
+
};
|
|
74
142
|
const _onMessage = this.onMessage.bind(this);
|
|
75
143
|
this.onMessage = async (connection, message) => {
|
|
76
|
-
return
|
|
144
|
+
return agentContext.run(
|
|
77
145
|
{ agent: this, connection, request: void 0 },
|
|
78
146
|
async () => {
|
|
79
147
|
if (typeof message !== "string") {
|
|
@@ -132,7 +200,7 @@ var Agent = class extends Server {
|
|
|
132
200
|
};
|
|
133
201
|
const _onConnect = this.onConnect.bind(this);
|
|
134
202
|
this.onConnect = (connection, ctx2) => {
|
|
135
|
-
return
|
|
203
|
+
return agentContext.run(
|
|
136
204
|
{ agent: this, connection, request: ctx2.request },
|
|
137
205
|
async () => {
|
|
138
206
|
setTimeout(() => {
|
|
@@ -214,7 +282,7 @@ var Agent = class extends Server {
|
|
|
214
282
|
* @param email Email message to process
|
|
215
283
|
*/
|
|
216
284
|
onEmail(email) {
|
|
217
|
-
return
|
|
285
|
+
return agentContext.run(
|
|
218
286
|
{ agent: this, connection: void 0, request: void 0 },
|
|
219
287
|
async () => {
|
|
220
288
|
console.error("onEmail not implemented");
|
|
@@ -377,45 +445,6 @@ var Agent = class extends Server {
|
|
|
377
445
|
await __privateMethod(this, _Agent_instances, scheduleNextAlarm_fn).call(this);
|
|
378
446
|
return true;
|
|
379
447
|
}
|
|
380
|
-
/**
|
|
381
|
-
* Method called when an alarm fires
|
|
382
|
-
* Executes any scheduled tasks that are due
|
|
383
|
-
*/
|
|
384
|
-
async alarm() {
|
|
385
|
-
const now = Math.floor(Date.now() / 1e3);
|
|
386
|
-
const result = this.sql`
|
|
387
|
-
SELECT * FROM cf_agents_schedules WHERE time <= ${now}
|
|
388
|
-
`;
|
|
389
|
-
for (const row of result || []) {
|
|
390
|
-
const callback = this[row.callback];
|
|
391
|
-
if (!callback) {
|
|
392
|
-
console.error(`callback ${row.callback} not found`);
|
|
393
|
-
continue;
|
|
394
|
-
}
|
|
395
|
-
await unstable_context.run(
|
|
396
|
-
{ agent: this, connection: void 0, request: void 0 },
|
|
397
|
-
async () => {
|
|
398
|
-
try {
|
|
399
|
-
await callback.bind(this)(JSON.parse(row.payload), row);
|
|
400
|
-
} catch (e) {
|
|
401
|
-
console.error(`error executing callback "${row.callback}"`, e);
|
|
402
|
-
}
|
|
403
|
-
}
|
|
404
|
-
);
|
|
405
|
-
if (row.type === "cron") {
|
|
406
|
-
const nextExecutionTime = getNextCronTime(row.cron);
|
|
407
|
-
const nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1e3);
|
|
408
|
-
this.sql`
|
|
409
|
-
UPDATE cf_agents_schedules SET time = ${nextTimestamp} WHERE id = ${row.id}
|
|
410
|
-
`;
|
|
411
|
-
} else {
|
|
412
|
-
this.sql`
|
|
413
|
-
DELETE FROM cf_agents_schedules WHERE id = ${row.id}
|
|
414
|
-
`;
|
|
415
|
-
}
|
|
416
|
-
}
|
|
417
|
-
await __privateMethod(this, _Agent_instances, scheduleNextAlarm_fn).call(this);
|
|
418
|
-
}
|
|
419
448
|
/**
|
|
420
449
|
* Destroy the Agent, removing all state and scheduled tasks
|
|
421
450
|
*/
|
|
@@ -427,6 +456,7 @@ var Agent = class extends Server {
|
|
|
427
456
|
}
|
|
428
457
|
};
|
|
429
458
|
_state = new WeakMap();
|
|
459
|
+
_ParentClass = new WeakMap();
|
|
430
460
|
_Agent_instances = new WeakSet();
|
|
431
461
|
setStateInternal_fn = function(state, source = "server") {
|
|
432
462
|
__privateSet(this, _state, state);
|
|
@@ -446,8 +476,8 @@ setStateInternal_fn = function(state, source = "server") {
|
|
|
446
476
|
source !== "server" ? [source.id] : []
|
|
447
477
|
);
|
|
448
478
|
return __privateMethod(this, _Agent_instances, tryCatch_fn).call(this, () => {
|
|
449
|
-
const { connection, request } =
|
|
450
|
-
return
|
|
479
|
+
const { connection, request } = agentContext.getStore() || {};
|
|
480
|
+
return agentContext.run(
|
|
451
481
|
{ agent: this, connection, request },
|
|
452
482
|
async () => {
|
|
453
483
|
return this.onStateUpdate(state, source);
|
|
@@ -527,7 +557,7 @@ async function routeAgentRequest(request, env, options) {
|
|
|
527
557
|
}
|
|
528
558
|
async function routeAgentEmail(email, env, options) {
|
|
529
559
|
}
|
|
530
|
-
function getAgentByName(namespace, name, options) {
|
|
560
|
+
async function getAgentByName(namespace, name, options) {
|
|
531
561
|
return getServerByName(namespace, name, options);
|
|
532
562
|
}
|
|
533
563
|
var _connection, _id, _closed;
|
|
@@ -581,11 +611,11 @@ _closed = new WeakMap();
|
|
|
581
611
|
|
|
582
612
|
export {
|
|
583
613
|
unstable_callable,
|
|
584
|
-
|
|
614
|
+
getCurrentAgent,
|
|
585
615
|
Agent,
|
|
586
616
|
routeAgentRequest,
|
|
587
617
|
routeAgentEmail,
|
|
588
618
|
getAgentByName,
|
|
589
619
|
StreamingResponse
|
|
590
620
|
};
|
|
591
|
-
//# sourceMappingURL=chunk-
|
|
621
|
+
//# sourceMappingURL=chunk-JR3NW4A7.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import {\n Server,\n routePartykitRequest,\n type PartyServerOptions,\n getServerByName,\n type Connection,\n type ConnectionContext,\n type WSMessage,\n} from \"partyserver\";\n\nimport { parseCronExpression } from \"cron-schedule\";\nimport { nanoid } from \"nanoid\";\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { MCPClientManager } from \"./mcp/client\";\n\nexport type { Connection, WSMessage, ConnectionContext } from \"partyserver\";\n\n/**\n * RPC request message from client\n */\nexport type RPCRequest = {\n type: \"rpc\";\n id: string;\n method: string;\n args: unknown[];\n};\n\n/**\n * State update message from client\n */\nexport type StateUpdateMessage = {\n type: \"cf_agent_state\";\n state: unknown;\n};\n\n/**\n * RPC response message to client\n */\nexport type RPCResponse = {\n type: \"rpc\";\n id: string;\n} & (\n | {\n success: true;\n result: unknown;\n done?: false;\n }\n | {\n success: true;\n result: unknown;\n done: true;\n }\n | {\n success: false;\n error: string;\n }\n);\n\n/**\n * Type guard for RPC request messages\n */\nfunction isRPCRequest(msg: unknown): msg is RPCRequest {\n return (\n typeof msg === \"object\" &&\n msg !== null &&\n \"type\" in msg &&\n msg.type === \"rpc\" &&\n \"id\" in msg &&\n typeof msg.id === \"string\" &&\n \"method\" in msg &&\n typeof msg.method === \"string\" &&\n \"args\" in msg &&\n Array.isArray((msg as RPCRequest).args)\n );\n}\n\n/**\n * Type guard for state update messages\n */\nfunction isStateUpdateMessage(msg: unknown): msg is StateUpdateMessage {\n return (\n typeof msg === \"object\" &&\n msg !== null &&\n \"type\" in msg &&\n msg.type === \"cf_agent_state\" &&\n \"state\" in msg\n );\n}\n\n/**\n * Metadata for a callable method\n */\nexport type CallableMetadata = {\n /** Optional description of what the method does */\n description?: string;\n /** Whether the method supports streaming responses */\n streaming?: boolean;\n};\n\n// biome-ignore lint/complexity/noBannedTypes: <explanation>\nconst callableMetadata = new Map<Function, CallableMetadata>();\n\n/**\n * Decorator that marks a method as callable by clients\n * @param metadata Optional metadata about the callable method\n */\nexport function unstable_callable(metadata: CallableMetadata = {}) {\n return function callableDecorator<This, Args extends unknown[], Return>(\n target: (this: This, ...args: Args) => Return,\n context: ClassMethodDecoratorContext\n ) {\n if (!callableMetadata.has(target)) {\n callableMetadata.set(target, metadata);\n }\n\n return target;\n };\n}\n\n/**\n * Represents a scheduled task within an Agent\n * @template T Type of the payload data\n */\nexport type Schedule<T = string> = {\n /** Unique identifier for the schedule */\n id: string;\n /** Name of the method to be called */\n callback: string;\n /** Data to be passed to the callback */\n payload: T;\n} & (\n | {\n /** Type of schedule for one-time execution at a specific time */\n type: \"scheduled\";\n /** Timestamp when the task should execute */\n time: number;\n }\n | {\n /** Type of schedule for delayed execution */\n type: \"delayed\";\n /** Timestamp when the task should execute */\n time: number;\n /** Number of seconds to delay execution */\n delayInSeconds: number;\n }\n | {\n /** Type of schedule for recurring execution based on cron expression */\n type: \"cron\";\n /** Timestamp for the next execution */\n time: number;\n /** Cron expression defining the schedule */\n cron: string;\n }\n);\n\nfunction getNextCronTime(cron: string) {\n const interval = parseCronExpression(cron);\n return interval.getNextDate();\n}\n\nconst STATE_ROW_ID = \"cf_state_row_id\";\nconst STATE_WAS_CHANGED = \"cf_state_was_changed\";\n\nconst DEFAULT_STATE = {} as unknown;\n\nconst agentContext = new AsyncLocalStorage<{\n agent: Agent<unknown>;\n connection: Connection | undefined;\n request: Request | undefined;\n}>();\n\nexport function getCurrentAgent<\n T extends Agent<unknown, unknown> = Agent<unknown, unknown>,\n>(): {\n agent: T | undefined;\n connection: Connection | undefined;\n request: Request<unknown, CfProperties<unknown>> | undefined;\n} {\n const store = agentContext.getStore() as\n | {\n agent: T;\n connection: Connection | undefined;\n request: Request<unknown, CfProperties<unknown>> | undefined;\n }\n | undefined;\n if (!store) {\n return {\n agent: undefined,\n connection: undefined,\n request: undefined,\n };\n }\n return store;\n}\n\n/**\n * Base class for creating Agent implementations\n * @template Env Environment type containing bindings\n * @template State State type to store within the Agent\n */\nexport class Agent<Env, State = unknown> extends Server<Env> {\n #state = DEFAULT_STATE as State;\n\n #ParentClass: typeof Agent<Env, State> =\n Object.getPrototypeOf(this).constructor;\n\n mcp: MCPClientManager = new MCPClientManager(this.#ParentClass.name, \"0.0.1\");\n\n /**\n * Initial state for the Agent\n * Override to provide default state values\n */\n initialState: State = DEFAULT_STATE as State;\n\n /**\n * Current state of the Agent\n */\n get state(): State {\n if (this.#state !== DEFAULT_STATE) {\n // state was previously set, and populated internal state\n return this.#state;\n }\n // looks like this is the first time the state is being accessed\n // check if the state was set in a previous life\n const wasChanged = this.sql<{ state: \"true\" | undefined }>`\n SELECT state FROM cf_agents_state WHERE id = ${STATE_WAS_CHANGED}\n `;\n\n // ok, let's pick up the actual state from the db\n const result = this.sql<{ state: State | undefined }>`\n SELECT state FROM cf_agents_state WHERE id = ${STATE_ROW_ID}\n `;\n\n if (\n wasChanged[0]?.state === \"true\" ||\n // we do this check for people who updated their code before we shipped wasChanged\n result[0]?.state\n ) {\n const state = result[0]?.state as string; // could be null?\n\n this.#state = JSON.parse(state);\n return this.#state;\n }\n\n // ok, this is the first time the state is being accessed\n // and the state was not set in a previous life\n // so we need to set the initial state (if provided)\n if (this.initialState === DEFAULT_STATE) {\n // no initial state provided, so we return undefined\n return undefined as State;\n }\n // initial state provided, so we set the state,\n // update db and return the initial state\n this.setState(this.initialState);\n return this.initialState;\n }\n\n /**\n * Agent configuration options\n */\n static options = {\n /** Whether the Agent should hibernate when inactive */\n hibernate: true, // default to hibernate\n };\n\n /**\n * Execute SQL queries against the Agent's database\n * @template T Type of the returned rows\n * @param strings SQL query template strings\n * @param values Values to be inserted into the query\n * @returns Array of query results\n */\n sql<T = Record<string, string | number | boolean | null>>(\n strings: TemplateStringsArray,\n ...values: (string | number | boolean | null)[]\n ) {\n let query = \"\";\n try {\n // Construct the SQL query with placeholders\n query = strings.reduce(\n (acc, str, i) => acc + str + (i < values.length ? \"?\" : \"\"),\n \"\"\n );\n\n // Execute the SQL query with the provided values\n return [...this.ctx.storage.sql.exec(query, ...values)] as T[];\n } catch (e) {\n console.error(`failed to execute sql query: ${query}`, e);\n throw this.onError(e);\n }\n }\n constructor(ctx: AgentContext, env: Env) {\n super(ctx, env);\n\n this.sql`\n CREATE TABLE IF NOT EXISTS cf_agents_state (\n id TEXT PRIMARY KEY NOT NULL,\n state TEXT\n )\n `;\n\n void this.ctx.blockConcurrencyWhile(async () => {\n return this.#tryCatch(async () => {\n // Create alarms table if it doesn't exist\n this.sql`\n CREATE TABLE IF NOT EXISTS cf_agents_schedules (\n id TEXT PRIMARY KEY NOT NULL DEFAULT (randomblob(9)),\n callback TEXT,\n payload TEXT,\n type TEXT NOT NULL CHECK(type IN ('scheduled', 'delayed', 'cron')),\n time INTEGER,\n delayInSeconds INTEGER,\n cron TEXT,\n created_at INTEGER DEFAULT (unixepoch())\n )\n `;\n\n // execute any pending alarms and schedule the next alarm\n await this.alarm();\n });\n });\n\n const _onRequest = this.onRequest.bind(this);\n this.onRequest = (request: Request) => {\n return agentContext.run(\n { agent: this, connection: undefined, request },\n async () => {\n return this.#tryCatch(() => _onRequest(request));\n }\n );\n };\n\n const _onMessage = this.onMessage.bind(this);\n this.onMessage = async (connection: Connection, message: WSMessage) => {\n return agentContext.run(\n { agent: this, connection, request: undefined },\n async () => {\n if (typeof message !== \"string\") {\n return this.#tryCatch(() => _onMessage(connection, message));\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(message);\n } catch (e) {\n // silently fail and let the onMessage handler handle it\n return this.#tryCatch(() => _onMessage(connection, message));\n }\n\n if (isStateUpdateMessage(parsed)) {\n this.#setStateInternal(parsed.state as State, connection);\n return;\n }\n\n if (isRPCRequest(parsed)) {\n try {\n const { id, method, args } = parsed;\n\n // Check if method exists and is callable\n const methodFn = this[method as keyof this];\n if (typeof methodFn !== \"function\") {\n throw new Error(`Method ${method} does not exist`);\n }\n\n if (!this.#isCallable(method)) {\n throw new Error(`Method ${method} is not callable`);\n }\n\n // biome-ignore lint/complexity/noBannedTypes: <explanation>\n const metadata = callableMetadata.get(methodFn as Function);\n\n // For streaming methods, pass a StreamingResponse object\n if (metadata?.streaming) {\n const stream = new StreamingResponse(connection, id);\n await methodFn.apply(this, [stream, ...args]);\n return;\n }\n\n // For regular methods, execute and send response\n const result = await methodFn.apply(this, args);\n const response: RPCResponse = {\n type: \"rpc\",\n id,\n success: true,\n result,\n done: true,\n };\n connection.send(JSON.stringify(response));\n } catch (e) {\n // Send error response\n const response: RPCResponse = {\n type: \"rpc\",\n id: parsed.id,\n success: false,\n error:\n e instanceof Error ? e.message : \"Unknown error occurred\",\n };\n connection.send(JSON.stringify(response));\n console.error(\"RPC error:\", e);\n }\n return;\n }\n\n return this.#tryCatch(() => _onMessage(connection, message));\n }\n );\n };\n\n const _onConnect = this.onConnect.bind(this);\n this.onConnect = (connection: Connection, ctx: ConnectionContext) => {\n // TODO: This is a hack to ensure the state is sent after the connection is established\n // must fix this\n return agentContext.run(\n { agent: this, connection, request: ctx.request },\n async () => {\n setTimeout(() => {\n if (this.state) {\n connection.send(\n JSON.stringify({\n type: \"cf_agent_state\",\n state: this.state,\n })\n );\n }\n return this.#tryCatch(() => _onConnect(connection, ctx));\n }, 20);\n }\n );\n };\n }\n\n #setStateInternal(state: State, source: Connection | \"server\" = \"server\") {\n this.#state = state;\n this.sql`\n INSERT OR REPLACE INTO cf_agents_state (id, state)\n VALUES (${STATE_ROW_ID}, ${JSON.stringify(state)})\n `;\n this.sql`\n INSERT OR REPLACE INTO cf_agents_state (id, state)\n VALUES (${STATE_WAS_CHANGED}, ${JSON.stringify(true)})\n `;\n this.broadcast(\n JSON.stringify({\n type: \"cf_agent_state\",\n state: state,\n }),\n source !== \"server\" ? [source.id] : []\n );\n return this.#tryCatch(() => {\n const { connection, request } = agentContext.getStore() || {};\n return agentContext.run(\n { agent: this, connection, request },\n async () => {\n return this.onStateUpdate(state, source);\n }\n );\n });\n }\n\n /**\n * Update the Agent's state\n * @param state New state to set\n */\n setState(state: State) {\n this.#setStateInternal(state, \"server\");\n }\n\n /**\n * Called when the Agent's state is updated\n * @param state Updated state\n * @param source Source of the state update (\"server\" or a client connection)\n */\n onStateUpdate(state: State | undefined, source: Connection | \"server\") {\n // override this to handle state updates\n }\n\n /**\n * Called when the Agent receives an email\n * @param email Email message to process\n */\n onEmail(email: ForwardableEmailMessage) {\n return agentContext.run(\n { agent: this, connection: undefined, request: undefined },\n async () => {\n console.error(\"onEmail not implemented\");\n }\n );\n }\n\n async #tryCatch<T>(fn: () => T | Promise<T>) {\n try {\n return await fn();\n } catch (e) {\n throw this.onError(e);\n }\n }\n\n override onError(\n connection: Connection,\n error: unknown\n ): void | Promise<void>;\n override onError(error: unknown): void | Promise<void>;\n override onError(connectionOrError: Connection | unknown, error?: unknown) {\n let theError: unknown;\n if (connectionOrError && error) {\n theError = error;\n // this is a websocket connection error\n console.error(\n \"Error on websocket connection:\",\n (connectionOrError as Connection).id,\n theError\n );\n console.error(\n \"Override onError(connection, error) to handle websocket connection errors\"\n );\n } else {\n theError = connectionOrError;\n // this is a server error\n console.error(\"Error on server:\", theError);\n console.error(\"Override onError(error) to handle server errors\");\n }\n throw theError;\n }\n\n /**\n * Render content (not implemented in base class)\n */\n render() {\n throw new Error(\"Not implemented\");\n }\n\n /**\n * Schedule a task to be executed in the future\n * @template T Type of the payload data\n * @param when When to execute the task (Date, seconds delay, or cron expression)\n * @param callback Name of the method to call\n * @param payload Data to pass to the callback\n * @returns Schedule object representing the scheduled task\n */\n async schedule<T = string>(\n when: Date | string | number,\n callback: keyof this,\n payload?: T\n ): Promise<Schedule<T>> {\n const id = nanoid(9);\n\n if (typeof callback !== \"string\") {\n throw new Error(\"Callback must be a string\");\n }\n\n if (typeof this[callback] !== \"function\") {\n throw new Error(`this.${callback} is not a function`);\n }\n\n if (when instanceof Date) {\n const timestamp = Math.floor(when.getTime() / 1000);\n this.sql`\n INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, time)\n VALUES (${id}, ${callback}, ${JSON.stringify(\n payload\n )}, 'scheduled', ${timestamp})\n `;\n\n await this.#scheduleNextAlarm();\n\n return {\n id,\n callback: callback,\n payload: payload as T,\n time: timestamp,\n type: \"scheduled\",\n };\n }\n if (typeof when === \"number\") {\n const time = new Date(Date.now() + when * 1000);\n const timestamp = Math.floor(time.getTime() / 1000);\n\n this.sql`\n INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, delayInSeconds, time)\n VALUES (${id}, ${callback}, ${JSON.stringify(\n payload\n )}, 'delayed', ${when}, ${timestamp})\n `;\n\n await this.#scheduleNextAlarm();\n\n return {\n id,\n callback: callback,\n payload: payload as T,\n delayInSeconds: when,\n time: timestamp,\n type: \"delayed\",\n };\n }\n if (typeof when === \"string\") {\n const nextExecutionTime = getNextCronTime(when);\n const timestamp = Math.floor(nextExecutionTime.getTime() / 1000);\n\n this.sql`\n INSERT OR REPLACE INTO cf_agents_schedules (id, callback, payload, type, cron, time)\n VALUES (${id}, ${callback}, ${JSON.stringify(\n payload\n )}, 'cron', ${when}, ${timestamp})\n `;\n\n await this.#scheduleNextAlarm();\n\n return {\n id,\n callback: callback,\n payload: payload as T,\n cron: when,\n time: timestamp,\n type: \"cron\",\n };\n }\n throw new Error(\"Invalid schedule type\");\n }\n\n /**\n * Get a scheduled task by ID\n * @template T Type of the payload data\n * @param id ID of the scheduled task\n * @returns The Schedule object or undefined if not found\n */\n async getSchedule<T = string>(id: string): Promise<Schedule<T> | undefined> {\n const result = this.sql<Schedule<string>>`\n SELECT * FROM cf_agents_schedules WHERE id = ${id}\n `;\n if (!result) {\n console.error(`schedule ${id} not found`);\n return undefined;\n }\n\n return { ...result[0], payload: JSON.parse(result[0].payload) as T };\n }\n\n /**\n * Get scheduled tasks matching the given criteria\n * @template T Type of the payload data\n * @param criteria Criteria to filter schedules\n * @returns Array of matching Schedule objects\n */\n getSchedules<T = string>(\n criteria: {\n id?: string;\n type?: \"scheduled\" | \"delayed\" | \"cron\";\n timeRange?: { start?: Date; end?: Date };\n } = {}\n ): Schedule<T>[] {\n let query = \"SELECT * FROM cf_agents_schedules WHERE 1=1\";\n const params = [];\n\n if (criteria.id) {\n query += \" AND id = ?\";\n params.push(criteria.id);\n }\n\n if (criteria.type) {\n query += \" AND type = ?\";\n params.push(criteria.type);\n }\n\n if (criteria.timeRange) {\n query += \" AND time >= ? AND time <= ?\";\n const start = criteria.timeRange.start || new Date(0);\n const end = criteria.timeRange.end || new Date(999999999999999);\n params.push(\n Math.floor(start.getTime() / 1000),\n Math.floor(end.getTime() / 1000)\n );\n }\n\n const result = this.ctx.storage.sql\n .exec(query, ...params)\n .toArray()\n .map((row) => ({\n ...row,\n payload: JSON.parse(row.payload as string) as T,\n })) as Schedule<T>[];\n\n return result;\n }\n\n /**\n * Cancel a scheduled task\n * @param id ID of the task to cancel\n * @returns true if the task was cancelled, false otherwise\n */\n async cancelSchedule(id: string): Promise<boolean> {\n this.sql`DELETE FROM cf_agents_schedules WHERE id = ${id}`;\n\n await this.#scheduleNextAlarm();\n return true;\n }\n\n async #scheduleNextAlarm() {\n // Find the next schedule that needs to be executed\n const result = this.sql`\n SELECT time FROM cf_agents_schedules \n WHERE time > ${Math.floor(Date.now() / 1000)}\n ORDER BY time ASC \n LIMIT 1\n `;\n if (!result) return;\n\n if (result.length > 0 && \"time\" in result[0]) {\n const nextTime = (result[0].time as number) * 1000;\n await this.ctx.storage.setAlarm(nextTime);\n }\n }\n\n /**\n * Method called when an alarm fires.\n * Executes any scheduled tasks that are due.\n *\n * @remarks\n * To schedule a task, please use the `this.schedule` method instead.\n * See {@link https://developers.cloudflare.com/agents/api-reference/schedule-tasks/}\n */\n public readonly alarm = async () => {\n const now = Math.floor(Date.now() / 1000);\n\n // Get all schedules that should be executed now\n const result = this.sql<Schedule<string>>`\n SELECT * FROM cf_agents_schedules WHERE time <= ${now}\n `;\n\n for (const row of result || []) {\n const callback = this[row.callback as keyof Agent<Env>];\n if (!callback) {\n console.error(`callback ${row.callback} not found`);\n continue;\n }\n await agentContext.run(\n { agent: this, connection: undefined, request: undefined },\n async () => {\n try {\n await (\n callback as (\n payload: unknown,\n schedule: Schedule<unknown>\n ) => Promise<void>\n ).bind(this)(JSON.parse(row.payload as string), row);\n } catch (e) {\n console.error(`error executing callback \"${row.callback}\"`, e);\n }\n }\n );\n if (row.type === \"cron\") {\n // Update next execution time for cron schedules\n const nextExecutionTime = getNextCronTime(row.cron);\n const nextTimestamp = Math.floor(nextExecutionTime.getTime() / 1000);\n\n this.sql`\n UPDATE cf_agents_schedules SET time = ${nextTimestamp} WHERE id = ${row.id}\n `;\n } else {\n // Delete one-time schedules after execution\n this.sql`\n DELETE FROM cf_agents_schedules WHERE id = ${row.id}\n `;\n }\n }\n\n // Schedule the next alarm\n await this.#scheduleNextAlarm();\n };\n\n /**\n * Destroy the Agent, removing all state and scheduled tasks\n */\n async destroy() {\n // drop all tables\n this.sql`DROP TABLE IF EXISTS cf_agents_state`;\n this.sql`DROP TABLE IF EXISTS cf_agents_schedules`;\n\n // delete all alarms\n await this.ctx.storage.deleteAlarm();\n await this.ctx.storage.deleteAll();\n }\n\n /**\n * Get all methods marked as callable on this Agent\n * @returns A map of method names to their metadata\n */\n #isCallable(method: string): boolean {\n // biome-ignore lint/complexity/noBannedTypes: <explanation>\n return callableMetadata.has(this[method as keyof this] as Function);\n }\n}\n\n/**\n * Namespace for creating Agent instances\n * @template Agentic Type of the Agent class\n */\nexport type AgentNamespace<Agentic extends Agent<unknown>> =\n DurableObjectNamespace<Agentic>;\n\n/**\n * Agent's durable context\n */\nexport type AgentContext = DurableObjectState;\n\n/**\n * Configuration options for Agent routing\n */\nexport type AgentOptions<Env> = PartyServerOptions<Env> & {\n /**\n * Whether to enable CORS for the Agent\n */\n cors?: boolean | HeadersInit | undefined;\n};\n\n/**\n * Route a request to the appropriate Agent\n * @param request Request to route\n * @param env Environment containing Agent bindings\n * @param options Routing options\n * @returns Response from the Agent or undefined if no route matched\n */\nexport async function routeAgentRequest<Env>(\n request: Request,\n env: Env,\n options?: AgentOptions<Env>\n) {\n const corsHeaders =\n options?.cors === true\n ? {\n \"Access-Control-Allow-Origin\": \"*\",\n \"Access-Control-Allow-Methods\": \"GET, POST, HEAD, OPTIONS\",\n \"Access-Control-Allow-Credentials\": \"true\",\n \"Access-Control-Max-Age\": \"86400\",\n }\n : options?.cors;\n\n if (request.method === \"OPTIONS\") {\n if (corsHeaders) {\n return new Response(null, {\n headers: corsHeaders,\n });\n }\n console.warn(\n \"Received an OPTIONS request, but cors was not enabled. Pass `cors: true` or `cors: { ...custom cors headers }` to routeAgentRequest to enable CORS.\"\n );\n }\n\n let response = await routePartykitRequest(\n request,\n env as Record<string, unknown>,\n {\n prefix: \"agents\",\n ...(options as PartyServerOptions<Record<string, unknown>>),\n }\n );\n\n if (\n response &&\n corsHeaders &&\n request.headers.get(\"upgrade\")?.toLowerCase() !== \"websocket\" &&\n request.headers.get(\"Upgrade\")?.toLowerCase() !== \"websocket\"\n ) {\n response = new Response(response.body, {\n headers: {\n ...response.headers,\n ...corsHeaders,\n },\n });\n }\n return response;\n}\n\n/**\n * Route an email to the appropriate Agent\n * @param email Email message to route\n * @param env Environment containing Agent bindings\n * @param options Routing options\n */\nexport async function routeAgentEmail<Env>(\n email: ForwardableEmailMessage,\n env: Env,\n options?: AgentOptions<Env>\n): Promise<void> {}\n\n/**\n * Get or create an Agent by name\n * @template Env Environment type containing bindings\n * @template T Type of the Agent class\n * @param namespace Agent namespace\n * @param name Name of the Agent instance\n * @param options Options for Agent creation\n * @returns Promise resolving to an Agent instance stub\n */\nexport async function getAgentByName<Env, T extends Agent<Env>>(\n namespace: AgentNamespace<T>,\n name: string,\n options?: {\n jurisdiction?: DurableObjectJurisdiction;\n locationHint?: DurableObjectLocationHint;\n }\n) {\n return getServerByName<Env, T>(namespace, name, options);\n}\n\n/**\n * A wrapper for streaming responses in callable methods\n */\nexport class StreamingResponse {\n #connection: Connection;\n #id: string;\n #closed = false;\n\n constructor(connection: Connection, id: string) {\n this.#connection = connection;\n this.#id = id;\n }\n\n /**\n * Send a chunk of data to the client\n * @param chunk The data to send\n */\n send(chunk: unknown) {\n if (this.#closed) {\n throw new Error(\"StreamingResponse is already closed\");\n }\n const response: RPCResponse = {\n type: \"rpc\",\n id: this.#id,\n success: true,\n result: chunk,\n done: false,\n };\n this.#connection.send(JSON.stringify(response));\n }\n\n /**\n * End the stream and send the final chunk (if any)\n * @param finalChunk Optional final chunk of data to send\n */\n end(finalChunk?: unknown) {\n if (this.#closed) {\n throw new Error(\"StreamingResponse is already closed\");\n }\n this.#closed = true;\n const response: RPCResponse = {\n type: \"rpc\",\n id: this.#id,\n success: true,\n result: finalChunk,\n done: true,\n };\n this.#connection.send(JSON.stringify(response));\n }\n}\n"],"mappings":";;;;;;;;;;;AAAA;AAAA,EACE;AAAA,EACA;AAAA,EAEA;AAAA,OAIK;AAEP,SAAS,2BAA2B;AACpC,SAAS,cAAc;AAEvB,SAAS,yBAAyB;AAiDlC,SAAS,aAAa,KAAiC;AACrD,SACE,OAAO,QAAQ,YACf,QAAQ,QACR,UAAU,OACV,IAAI,SAAS,SACb,QAAQ,OACR,OAAO,IAAI,OAAO,YAClB,YAAY,OACZ,OAAO,IAAI,WAAW,YACtB,UAAU,OACV,MAAM,QAAS,IAAmB,IAAI;AAE1C;AAKA,SAAS,qBAAqB,KAAyC;AACrE,SACE,OAAO,QAAQ,YACf,QAAQ,QACR,UAAU,OACV,IAAI,SAAS,oBACb,WAAW;AA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,EACb;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,KAAK,OAAgB;AACnB,QAAI,mBAAK,UAAS;AAChB,YAAM,IAAI,MAAM,qCAAqC;AAAA,IACvD;AACA,UAAM,WAAwB;AAAA,MAC5B,MAAM;AAAA,MACN,IAAI,mBAAK;AAAA,MACT,SAAS;AAAA,MACT,QAAQ;AAAA,MACR,MAAM;AAAA,IACR;AACA,uBAAK,aAAY,KAAK,KAAK,UAAU,QAAQ,CAAC;AAAA,EAChD;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,IAAI,YAAsB;AACxB,QAAI,mBAAK,UAAS;AAChB,YAAM,IAAI,MAAM,qCAAqC;AAAA,IACvD;AACA,uBAAK,SAAU;AACf,UAAM,WAAwB;AAAA,MAC5B,MAAM;AAAA,MACN,IAAI,mBAAK;AAAA,MACT,SAAS;AAAA,MACT,QAAQ;AAAA,MACR,MAAM;AAAA,IACR;AACA,uBAAK,aAAY,KAAK,KAAK,UAAU,QAAQ,CAAC;AAAA,EAChD;AACF;AA7CE;AACA;AACA;","names":["ctx"]}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,15 @@
|
|
|
1
1
|
import { Server, Connection, PartyServerOptions } from "partyserver";
|
|
2
2
|
export { Connection, ConnectionContext, WSMessage } from "partyserver";
|
|
3
|
-
import {
|
|
3
|
+
import { MCPClientManager } from "./mcp/client.js";
|
|
4
|
+
import "zod";
|
|
5
|
+
import "@modelcontextprotocol/sdk/types.js";
|
|
6
|
+
import "@modelcontextprotocol/sdk/client/index.js";
|
|
7
|
+
import "@modelcontextprotocol/sdk/client/sse.js";
|
|
8
|
+
import "./mcp/do-oauth-client-provider.js";
|
|
9
|
+
import "@modelcontextprotocol/sdk/client/auth.js";
|
|
10
|
+
import "@modelcontextprotocol/sdk/shared/auth.js";
|
|
11
|
+
import "@modelcontextprotocol/sdk/shared/protocol.js";
|
|
12
|
+
import "ai";
|
|
4
13
|
|
|
5
14
|
/**
|
|
6
15
|
* RPC request message from client
|
|
@@ -94,11 +103,13 @@ type Schedule<T = string> = {
|
|
|
94
103
|
cron: string;
|
|
95
104
|
}
|
|
96
105
|
);
|
|
97
|
-
declare
|
|
98
|
-
|
|
106
|
+
declare function getCurrentAgent<
|
|
107
|
+
T extends Agent<unknown, unknown> = Agent<unknown, unknown>,
|
|
108
|
+
>(): {
|
|
109
|
+
agent: T | undefined;
|
|
99
110
|
connection: Connection | undefined;
|
|
100
|
-
request: Request | undefined;
|
|
101
|
-
}
|
|
111
|
+
request: Request<unknown, CfProperties<unknown>> | undefined;
|
|
112
|
+
};
|
|
102
113
|
/**
|
|
103
114
|
* Base class for creating Agent implementations
|
|
104
115
|
* @template Env Environment type containing bindings
|
|
@@ -106,6 +117,7 @@ declare const unstable_context: AsyncLocalStorage<{
|
|
|
106
117
|
*/
|
|
107
118
|
declare class Agent<Env, State = unknown> extends Server<Env> {
|
|
108
119
|
#private;
|
|
120
|
+
mcp: MCPClientManager;
|
|
109
121
|
/**
|
|
110
122
|
* Initial state for the Agent
|
|
111
123
|
* Override to provide default state values
|
|
@@ -197,10 +209,14 @@ declare class Agent<Env, State = unknown> extends Server<Env> {
|
|
|
197
209
|
*/
|
|
198
210
|
cancelSchedule(id: string): Promise<boolean>;
|
|
199
211
|
/**
|
|
200
|
-
* Method called when an alarm fires
|
|
201
|
-
* Executes any scheduled tasks that are due
|
|
212
|
+
* Method called when an alarm fires.
|
|
213
|
+
* Executes any scheduled tasks that are due.
|
|
214
|
+
*
|
|
215
|
+
* @remarks
|
|
216
|
+
* To schedule a task, please use the `this.schedule` method instead.
|
|
217
|
+
* See {@link https://developers.cloudflare.com/agents/api-reference/schedule-tasks/}
|
|
202
218
|
*/
|
|
203
|
-
alarm()
|
|
219
|
+
readonly alarm: () => Promise<void>;
|
|
204
220
|
/**
|
|
205
221
|
* Destroy the Agent, removing all state and scheduled tasks
|
|
206
222
|
*/
|
|
@@ -295,8 +311,8 @@ export {
|
|
|
295
311
|
type StateUpdateMessage,
|
|
296
312
|
StreamingResponse,
|
|
297
313
|
getAgentByName,
|
|
314
|
+
getCurrentAgent,
|
|
298
315
|
routeAgentEmail,
|
|
299
316
|
routeAgentRequest,
|
|
300
317
|
unstable_callable,
|
|
301
|
-
unstable_context,
|
|
302
318
|
};
|
package/dist/index.js
CHANGED
|
@@ -2,19 +2,20 @@ import {
|
|
|
2
2
|
Agent,
|
|
3
3
|
StreamingResponse,
|
|
4
4
|
getAgentByName,
|
|
5
|
+
getCurrentAgent,
|
|
5
6
|
routeAgentEmail,
|
|
6
7
|
routeAgentRequest,
|
|
7
|
-
unstable_callable
|
|
8
|
-
|
|
9
|
-
|
|
8
|
+
unstable_callable
|
|
9
|
+
} from "./chunk-JR3NW4A7.js";
|
|
10
|
+
import "./chunk-7VFQNJFK.js";
|
|
10
11
|
import "./chunk-HMLY7DHA.js";
|
|
11
12
|
export {
|
|
12
13
|
Agent,
|
|
13
14
|
StreamingResponse,
|
|
14
15
|
getAgentByName,
|
|
16
|
+
getCurrentAgent,
|
|
15
17
|
routeAgentEmail,
|
|
16
18
|
routeAgentRequest,
|
|
17
|
-
unstable_callable
|
|
18
|
-
unstable_context
|
|
19
|
+
unstable_callable
|
|
19
20
|
};
|
|
20
21
|
//# sourceMappingURL=index.js.map
|
package/dist/mcp/client.d.ts
CHANGED
|
@@ -1,14 +1,22 @@
|
|
|
1
1
|
import * as zod from 'zod';
|
|
2
|
-
import { Tool, Prompt, Resource, ResourceTemplate, ServerCapabilities,
|
|
2
|
+
import { ClientCapabilities, Tool, Prompt, Resource, ResourceTemplate, ServerCapabilities, CallToolRequest, CallToolResultSchema, CompatibilityCallToolResultSchema, ReadResourceRequest, GetPromptRequest } from '@modelcontextprotocol/sdk/types.js';
|
|
3
3
|
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
|
|
4
4
|
import { SSEClientTransportOptions } from '@modelcontextprotocol/sdk/client/sse.js';
|
|
5
|
+
import { AgentsOAuthProvider } from './do-oauth-client-provider.js';
|
|
5
6
|
import { RequestOptions } from '@modelcontextprotocol/sdk/shared/protocol.js';
|
|
6
|
-
import {
|
|
7
|
+
import { ToolSet } from 'ai';
|
|
8
|
+
import '@modelcontextprotocol/sdk/client/auth.js';
|
|
9
|
+
import '@modelcontextprotocol/sdk/shared/auth.js';
|
|
7
10
|
|
|
8
11
|
declare class MCPClientConnection {
|
|
9
12
|
url: URL;
|
|
10
|
-
|
|
11
|
-
|
|
13
|
+
options: {
|
|
14
|
+
transport: SSEClientTransportOptions & {
|
|
15
|
+
authProvider?: AgentsOAuthProvider;
|
|
16
|
+
};
|
|
17
|
+
client: ConstructorParameters<typeof Client>[1];
|
|
18
|
+
capabilities: ClientCapabilities;
|
|
19
|
+
};
|
|
12
20
|
client: Client;
|
|
13
21
|
connectionState: "authenticating" | "connecting" | "ready" | "discovering" | "failed";
|
|
14
22
|
instructions?: string;
|
|
@@ -18,7 +26,9 @@ declare class MCPClientConnection {
|
|
|
18
26
|
resourceTemplates: ResourceTemplate[];
|
|
19
27
|
serverCapabilities: ServerCapabilities | undefined;
|
|
20
28
|
constructor(url: URL, info: ConstructorParameters<typeof Client>[0], options?: {
|
|
21
|
-
transport: SSEClientTransportOptions
|
|
29
|
+
transport: SSEClientTransportOptions & {
|
|
30
|
+
authProvider?: AgentsOAuthProvider;
|
|
31
|
+
};
|
|
22
32
|
client: ConstructorParameters<typeof Client>[1];
|
|
23
33
|
capabilities: ClientCapabilities;
|
|
24
34
|
});
|
|
@@ -47,13 +57,21 @@ declare class MCPClientConnection {
|
|
|
47
57
|
} | undefined;
|
|
48
58
|
};
|
|
49
59
|
description?: string | undefined;
|
|
60
|
+
annotations?: {
|
|
61
|
+
[x: string]: unknown;
|
|
62
|
+
title?: string | undefined;
|
|
63
|
+
readOnlyHint?: boolean | undefined;
|
|
64
|
+
destructiveHint?: boolean | undefined;
|
|
65
|
+
idempotentHint?: boolean | undefined;
|
|
66
|
+
openWorldHint?: boolean | undefined;
|
|
67
|
+
} | undefined;
|
|
50
68
|
}[]>;
|
|
51
69
|
fetchResources(): Promise<{
|
|
52
70
|
[x: string]: unknown;
|
|
53
|
-
name: string;
|
|
54
71
|
uri: string;
|
|
55
|
-
|
|
72
|
+
name: string;
|
|
56
73
|
mimeType?: string | undefined;
|
|
74
|
+
description?: string | undefined;
|
|
57
75
|
}[]>;
|
|
58
76
|
fetchPrompts(): Promise<{
|
|
59
77
|
[x: string]: unknown;
|
|
@@ -70,33 +88,25 @@ declare class MCPClientConnection {
|
|
|
70
88
|
[x: string]: unknown;
|
|
71
89
|
name: string;
|
|
72
90
|
uriTemplate: string;
|
|
73
|
-
description?: string | undefined;
|
|
74
91
|
mimeType?: string | undefined;
|
|
92
|
+
description?: string | undefined;
|
|
75
93
|
}[]>;
|
|
76
94
|
}
|
|
77
95
|
|
|
78
|
-
interface AgentsOAuthProvider extends OAuthClientProvider {
|
|
79
|
-
authUrl: string | undefined;
|
|
80
|
-
clientId: string | undefined;
|
|
81
|
-
}
|
|
82
|
-
|
|
83
96
|
/**
|
|
84
97
|
* Utility class that aggregates multiple MCP clients into one
|
|
85
98
|
*/
|
|
86
99
|
declare class MCPClientManager {
|
|
87
100
|
private name;
|
|
88
101
|
private version;
|
|
89
|
-
private auth?;
|
|
90
102
|
mcpConnections: Record<string, MCPClientConnection>;
|
|
103
|
+
private callbackUrls;
|
|
91
104
|
/**
|
|
92
105
|
* @param name Name of the MCP client
|
|
93
106
|
* @param version Version of the MCP Client
|
|
94
107
|
* @param auth Auth paramters if being used to create a DurableObjectOAuthClientProvider
|
|
95
108
|
*/
|
|
96
|
-
constructor(name: string, version: string
|
|
97
|
-
baseCallbackUri: string;
|
|
98
|
-
storage: DurableObjectStorage;
|
|
99
|
-
} | undefined);
|
|
109
|
+
constructor(name: string, version: string);
|
|
100
110
|
/**
|
|
101
111
|
* Connect to and register an MCP server
|
|
102
112
|
*
|
|
@@ -104,14 +114,14 @@ declare class MCPClientManager {
|
|
|
104
114
|
* @param clientConfig Client config
|
|
105
115
|
* @param capabilities Client capabilities (i.e. if the client supports roots/sampling)
|
|
106
116
|
*/
|
|
107
|
-
connect(url: string,
|
|
117
|
+
connect(url: string, options?: {
|
|
108
118
|
reconnect?: {
|
|
109
119
|
id: string;
|
|
110
120
|
oauthClientId?: string;
|
|
111
121
|
oauthCode?: string;
|
|
112
122
|
};
|
|
113
123
|
transport?: SSEClientTransportOptions & {
|
|
114
|
-
authProvider
|
|
124
|
+
authProvider?: AgentsOAuthProvider;
|
|
115
125
|
};
|
|
116
126
|
client?: ConstructorParameters<typeof Client>[1];
|
|
117
127
|
capabilities?: ClientCapabilities;
|
|
@@ -127,6 +137,19 @@ declare class MCPClientManager {
|
|
|
127
137
|
* @returns namespaced list of tools
|
|
128
138
|
*/
|
|
129
139
|
listTools(): NamespacedData["tools"];
|
|
140
|
+
/**
|
|
141
|
+
* @returns a set of tools that you can use with the AI SDK
|
|
142
|
+
*/
|
|
143
|
+
unstable_getAITools(): ToolSet;
|
|
144
|
+
/**
|
|
145
|
+
* Closes all connections to MCP servers
|
|
146
|
+
*/
|
|
147
|
+
closeAllConnections(): Promise<void[]>;
|
|
148
|
+
/**
|
|
149
|
+
* Closes a connection to an MCP server
|
|
150
|
+
* @param id The id of the connection to close
|
|
151
|
+
*/
|
|
152
|
+
closeConnection(id: string): Promise<void>;
|
|
130
153
|
/**
|
|
131
154
|
* @returns namespaced list of prompts
|
|
132
155
|
*/
|
|
@@ -144,9 +167,9 @@ declare class MCPClientManager {
|
|
|
144
167
|
*/
|
|
145
168
|
callTool(params: CallToolRequest["params"] & {
|
|
146
169
|
serverId: string;
|
|
147
|
-
}, resultSchema
|
|
170
|
+
}, resultSchema?: typeof CallToolResultSchema | typeof CompatibilityCallToolResultSchema, options?: RequestOptions): Promise<zod.objectOutputType<{
|
|
148
171
|
_meta: zod.ZodOptional<zod.ZodObject<{}, "passthrough", zod.ZodTypeAny, zod.objectOutputType<{}, zod.ZodTypeAny, "passthrough">, zod.objectInputType<{}, zod.ZodTypeAny, "passthrough">>>;
|
|
149
|
-
}
|
|
172
|
+
} & {
|
|
150
173
|
content: zod.ZodArray<zod.ZodUnion<[zod.ZodObject<{
|
|
151
174
|
type: zod.ZodLiteral<"text">;
|
|
152
175
|
text: zod.ZodString;
|
|
@@ -168,6 +191,18 @@ declare class MCPClientManager {
|
|
|
168
191
|
type: zod.ZodLiteral<"image">;
|
|
169
192
|
data: zod.ZodString;
|
|
170
193
|
mimeType: zod.ZodString;
|
|
194
|
+
}, zod.ZodTypeAny, "passthrough">>, zod.ZodObject<{
|
|
195
|
+
type: zod.ZodLiteral<"audio">;
|
|
196
|
+
data: zod.ZodString;
|
|
197
|
+
mimeType: zod.ZodString;
|
|
198
|
+
}, "passthrough", zod.ZodTypeAny, zod.objectOutputType<{
|
|
199
|
+
type: zod.ZodLiteral<"audio">;
|
|
200
|
+
data: zod.ZodString;
|
|
201
|
+
mimeType: zod.ZodString;
|
|
202
|
+
}, zod.ZodTypeAny, "passthrough">, zod.objectInputType<{
|
|
203
|
+
type: zod.ZodLiteral<"audio">;
|
|
204
|
+
data: zod.ZodString;
|
|
205
|
+
mimeType: zod.ZodString;
|
|
171
206
|
}, zod.ZodTypeAny, "passthrough">>, zod.ZodObject<{
|
|
172
207
|
type: zod.ZodLiteral<"resource">;
|
|
173
208
|
resource: zod.ZodUnion<[zod.ZodObject<zod.objectUtil.extendShape<{
|
|
@@ -269,19 +304,19 @@ declare class MCPClientManager {
|
|
|
269
304
|
}>, zod.ZodTypeAny, "passthrough">>]>;
|
|
270
305
|
}, zod.ZodTypeAny, "passthrough">>]>, "many">;
|
|
271
306
|
isError: zod.ZodOptional<zod.ZodDefault<zod.ZodBoolean>>;
|
|
272
|
-
}
|
|
307
|
+
}, zod.ZodTypeAny, "passthrough"> | zod.objectOutputType<{
|
|
273
308
|
_meta: zod.ZodOptional<zod.ZodObject<{}, "passthrough", zod.ZodTypeAny, zod.objectOutputType<{}, zod.ZodTypeAny, "passthrough">, zod.objectInputType<{}, zod.ZodTypeAny, "passthrough">>>;
|
|
274
|
-
}
|
|
309
|
+
} & {
|
|
275
310
|
toolResult: zod.ZodUnknown;
|
|
276
|
-
}
|
|
311
|
+
}, zod.ZodTypeAny, "passthrough">>;
|
|
277
312
|
/**
|
|
278
313
|
* Namespaced version of readResource
|
|
279
314
|
*/
|
|
280
315
|
readResource(params: ReadResourceRequest["params"] & {
|
|
281
316
|
serverId: string;
|
|
282
|
-
}, options: RequestOptions): Promise<zod.objectOutputType<
|
|
317
|
+
}, options: RequestOptions): Promise<zod.objectOutputType<{
|
|
283
318
|
_meta: zod.ZodOptional<zod.ZodObject<{}, "passthrough", zod.ZodTypeAny, zod.objectOutputType<{}, zod.ZodTypeAny, "passthrough">, zod.objectInputType<{}, zod.ZodTypeAny, "passthrough">>>;
|
|
284
|
-
}
|
|
319
|
+
} & {
|
|
285
320
|
contents: zod.ZodArray<zod.ZodUnion<[zod.ZodObject<zod.objectUtil.extendShape<{
|
|
286
321
|
uri: zod.ZodString;
|
|
287
322
|
mimeType: zod.ZodOptional<zod.ZodString>;
|
|
@@ -313,15 +348,15 @@ declare class MCPClientManager {
|
|
|
313
348
|
}, {
|
|
314
349
|
blob: zod.ZodString;
|
|
315
350
|
}>, zod.ZodTypeAny, "passthrough">>]>, "many">;
|
|
316
|
-
}
|
|
351
|
+
}, zod.ZodTypeAny, "passthrough">>;
|
|
317
352
|
/**
|
|
318
353
|
* Namespaced version of getPrompt
|
|
319
354
|
*/
|
|
320
355
|
getPrompt(params: GetPromptRequest["params"] & {
|
|
321
356
|
serverId: string;
|
|
322
|
-
}, options: RequestOptions): Promise<zod.objectOutputType<
|
|
357
|
+
}, options: RequestOptions): Promise<zod.objectOutputType<{
|
|
323
358
|
_meta: zod.ZodOptional<zod.ZodObject<{}, "passthrough", zod.ZodTypeAny, zod.objectOutputType<{}, zod.ZodTypeAny, "passthrough">, zod.objectInputType<{}, zod.ZodTypeAny, "passthrough">>>;
|
|
324
|
-
}
|
|
359
|
+
} & {
|
|
325
360
|
description: zod.ZodOptional<zod.ZodString>;
|
|
326
361
|
messages: zod.ZodArray<zod.ZodObject<{
|
|
327
362
|
role: zod.ZodEnum<["user", "assistant"]>;
|
|
@@ -346,6 +381,18 @@ declare class MCPClientManager {
|
|
|
346
381
|
type: zod.ZodLiteral<"image">;
|
|
347
382
|
data: zod.ZodString;
|
|
348
383
|
mimeType: zod.ZodString;
|
|
384
|
+
}, zod.ZodTypeAny, "passthrough">>, zod.ZodObject<{
|
|
385
|
+
type: zod.ZodLiteral<"audio">;
|
|
386
|
+
data: zod.ZodString;
|
|
387
|
+
mimeType: zod.ZodString;
|
|
388
|
+
}, "passthrough", zod.ZodTypeAny, zod.objectOutputType<{
|
|
389
|
+
type: zod.ZodLiteral<"audio">;
|
|
390
|
+
data: zod.ZodString;
|
|
391
|
+
mimeType: zod.ZodString;
|
|
392
|
+
}, zod.ZodTypeAny, "passthrough">, zod.objectInputType<{
|
|
393
|
+
type: zod.ZodLiteral<"audio">;
|
|
394
|
+
data: zod.ZodString;
|
|
395
|
+
mimeType: zod.ZodString;
|
|
349
396
|
}, zod.ZodTypeAny, "passthrough">>, zod.ZodObject<{
|
|
350
397
|
type: zod.ZodLiteral<"resource">;
|
|
351
398
|
resource: zod.ZodUnion<[zod.ZodObject<zod.objectUtil.extendShape<{
|
|
@@ -469,6 +516,18 @@ declare class MCPClientManager {
|
|
|
469
516
|
type: zod.ZodLiteral<"image">;
|
|
470
517
|
data: zod.ZodString;
|
|
471
518
|
mimeType: zod.ZodString;
|
|
519
|
+
}, zod.ZodTypeAny, "passthrough">>, zod.ZodObject<{
|
|
520
|
+
type: zod.ZodLiteral<"audio">;
|
|
521
|
+
data: zod.ZodString;
|
|
522
|
+
mimeType: zod.ZodString;
|
|
523
|
+
}, "passthrough", zod.ZodTypeAny, zod.objectOutputType<{
|
|
524
|
+
type: zod.ZodLiteral<"audio">;
|
|
525
|
+
data: zod.ZodString;
|
|
526
|
+
mimeType: zod.ZodString;
|
|
527
|
+
}, zod.ZodTypeAny, "passthrough">, zod.objectInputType<{
|
|
528
|
+
type: zod.ZodLiteral<"audio">;
|
|
529
|
+
data: zod.ZodString;
|
|
530
|
+
mimeType: zod.ZodString;
|
|
472
531
|
}, zod.ZodTypeAny, "passthrough">>, zod.ZodObject<{
|
|
473
532
|
type: zod.ZodLiteral<"resource">;
|
|
474
533
|
resource: zod.ZodUnion<[zod.ZodObject<zod.objectUtil.extendShape<{
|
|
@@ -592,6 +651,18 @@ declare class MCPClientManager {
|
|
|
592
651
|
type: zod.ZodLiteral<"image">;
|
|
593
652
|
data: zod.ZodString;
|
|
594
653
|
mimeType: zod.ZodString;
|
|
654
|
+
}, zod.ZodTypeAny, "passthrough">>, zod.ZodObject<{
|
|
655
|
+
type: zod.ZodLiteral<"audio">;
|
|
656
|
+
data: zod.ZodString;
|
|
657
|
+
mimeType: zod.ZodString;
|
|
658
|
+
}, "passthrough", zod.ZodTypeAny, zod.objectOutputType<{
|
|
659
|
+
type: zod.ZodLiteral<"audio">;
|
|
660
|
+
data: zod.ZodString;
|
|
661
|
+
mimeType: zod.ZodString;
|
|
662
|
+
}, zod.ZodTypeAny, "passthrough">, zod.objectInputType<{
|
|
663
|
+
type: zod.ZodLiteral<"audio">;
|
|
664
|
+
data: zod.ZodString;
|
|
665
|
+
mimeType: zod.ZodString;
|
|
595
666
|
}, zod.ZodTypeAny, "passthrough">>, zod.ZodObject<{
|
|
596
667
|
type: zod.ZodLiteral<"resource">;
|
|
597
668
|
resource: zod.ZodUnion<[zod.ZodObject<zod.objectUtil.extendShape<{
|
|
@@ -693,7 +764,7 @@ declare class MCPClientManager {
|
|
|
693
764
|
}>, zod.ZodTypeAny, "passthrough">>]>;
|
|
694
765
|
}, zod.ZodTypeAny, "passthrough">>]>;
|
|
695
766
|
}, zod.ZodTypeAny, "passthrough">>, "many">;
|
|
696
|
-
}
|
|
767
|
+
}, zod.ZodTypeAny, "passthrough">>;
|
|
697
768
|
}
|
|
698
769
|
type NamespacedData = {
|
|
699
770
|
tools: (Tool & {
|