agents 0.0.0-e48e5f9 → 0.0.0-e6dd636

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/README.md +357 -6
  2. package/dist/ai-chat-agent.d.ts +238 -29
  3. package/dist/ai-chat-agent.js +1118 -260
  4. package/dist/ai-chat-agent.js.map +1 -1
  5. package/dist/ai-chat-v5-migration.d.ts +155 -0
  6. package/dist/ai-chat-v5-migration.js +155 -0
  7. package/dist/ai-chat-v5-migration.js.map +1 -0
  8. package/dist/ai-react.d.ts +197 -84
  9. package/dist/ai-react.js +574 -199
  10. package/dist/ai-react.js.map +1 -1
  11. package/dist/ai-types-0OnT3FHg.d.ts +127 -0
  12. package/dist/ai-types-DEtF_8Km.js +28 -0
  13. package/dist/ai-types-DEtF_8Km.js.map +1 -0
  14. package/dist/ai-types.d.ts +6 -74
  15. package/dist/ai-types.js +3 -1
  16. package/dist/cli/index.d.ts +1 -0
  17. package/dist/cli/index.js +28 -0
  18. package/dist/cli/index.js.map +1 -0
  19. package/dist/client-BINtT7y-.d.ts +834 -0
  20. package/dist/client-CdM5I962.d.ts +104 -0
  21. package/dist/client-DjTPRM8-.js +117 -0
  22. package/dist/client-DjTPRM8-.js.map +1 -0
  23. package/dist/client-QZa2Rq0l.js +1105 -0
  24. package/dist/client-QZa2Rq0l.js.map +1 -0
  25. package/dist/client.d.ts +10 -92
  26. package/dist/client.js +3 -11
  27. package/dist/codemode/ai.d.ts +27 -0
  28. package/dist/codemode/ai.js +151 -0
  29. package/dist/codemode/ai.js.map +1 -0
  30. package/dist/context-BkKbAa1R.js +8 -0
  31. package/dist/context-BkKbAa1R.js.map +1 -0
  32. package/dist/context-DcbQ8o7k.d.ts +24 -0
  33. package/dist/context.d.ts +6 -0
  34. package/dist/context.js +3 -0
  35. package/dist/do-oauth-client-provider--To1Tsjj.d.ts +70 -0
  36. package/dist/do-oauth-client-provider-B1fVIshX.js +155 -0
  37. package/dist/do-oauth-client-provider-B1fVIshX.js.map +1 -0
  38. package/dist/{index-BIJvkfYt.d.ts → index-CxZRDFxS.d.ts} +133 -170
  39. package/dist/index-DLuxm_9W.d.ts +58 -0
  40. package/dist/index.d.ts +66 -38
  41. package/dist/index.js +7 -28
  42. package/dist/mcp/client.d.ts +2 -1055
  43. package/dist/mcp/client.js +4 -9
  44. package/dist/mcp/do-oauth-client-provider.d.ts +2 -41
  45. package/dist/mcp/do-oauth-client-provider.js +3 -7
  46. package/dist/mcp/index.d.ts +197 -81
  47. package/dist/mcp/index.js +1429 -770
  48. package/dist/mcp/index.js.map +1 -1
  49. package/dist/mcp/x402.d.ts +34 -0
  50. package/dist/mcp/x402.js +198 -0
  51. package/dist/mcp/x402.js.map +1 -0
  52. package/dist/mcp-CPSfGUgd.d.ts +61 -0
  53. package/dist/observability/index.d.ts +2 -12
  54. package/dist/observability/index.js +7 -10
  55. package/dist/react.d.ts +48 -33
  56. package/dist/react.js +183 -110
  57. package/dist/react.js.map +1 -1
  58. package/dist/schedule.d.ts +61 -38
  59. package/dist/schedule.js +46 -21
  60. package/dist/schedule.js.map +1 -1
  61. package/dist/serializable-Crsj26mx.d.ts +39 -0
  62. package/dist/serializable.d.ts +7 -32
  63. package/dist/serializable.js +1 -1
  64. package/dist/src-BZDh910Z.js +1181 -0
  65. package/dist/src-BZDh910Z.js.map +1 -0
  66. package/package.json +93 -29
  67. package/dist/ai-types.js.map +0 -1
  68. package/dist/chunk-5YIRLLUX.js +0 -1264
  69. package/dist/chunk-5YIRLLUX.js.map +0 -1
  70. package/dist/chunk-KUH345EY.js +0 -116
  71. package/dist/chunk-KUH345EY.js.map +0 -1
  72. package/dist/chunk-MW5BQ2FW.js +0 -469
  73. package/dist/chunk-MW5BQ2FW.js.map +0 -1
  74. package/dist/chunk-PVQZBKN7.js +0 -106
  75. package/dist/chunk-PVQZBKN7.js.map +0 -1
  76. package/dist/client.js.map +0 -1
  77. package/dist/index.js.map +0 -1
  78. package/dist/mcp/client.js.map +0 -1
  79. package/dist/mcp/do-oauth-client-provider.js.map +0 -1
  80. package/dist/observability/index.js.map +0 -1
  81. package/dist/serializable.js.map +0 -1
  82. package/src/index.ts +0 -1878
@@ -0,0 +1,155 @@
1
+ import { nanoid } from "nanoid";
2
+
3
+ //#region src/mcp/do-oauth-client-provider.ts
4
+ const STATE_EXPIRATION_MS = 600 * 1e3;
5
+ var DurableObjectOAuthClientProvider = class {
6
+ constructor(storage, clientName, baseRedirectUrl) {
7
+ this.storage = storage;
8
+ this.clientName = clientName;
9
+ this.baseRedirectUrl = baseRedirectUrl;
10
+ if (!storage) throw new Error("DurableObjectOAuthClientProvider requires a valid DurableObjectStorage instance");
11
+ }
12
+ get clientMetadata() {
13
+ return {
14
+ client_name: this.clientName,
15
+ client_uri: this.clientUri,
16
+ grant_types: ["authorization_code", "refresh_token"],
17
+ redirect_uris: [this.redirectUrl],
18
+ response_types: ["code"],
19
+ token_endpoint_auth_method: "none"
20
+ };
21
+ }
22
+ get clientUri() {
23
+ return new URL(this.redirectUrl).origin;
24
+ }
25
+ get redirectUrl() {
26
+ return this.baseRedirectUrl;
27
+ }
28
+ get clientId() {
29
+ if (!this._clientId_) throw new Error("Trying to access clientId before it was set");
30
+ return this._clientId_;
31
+ }
32
+ set clientId(clientId_) {
33
+ this._clientId_ = clientId_;
34
+ }
35
+ get serverId() {
36
+ if (!this._serverId_) throw new Error("Trying to access serverId before it was set");
37
+ return this._serverId_;
38
+ }
39
+ set serverId(serverId_) {
40
+ this._serverId_ = serverId_;
41
+ }
42
+ keyPrefix(clientId) {
43
+ return `/${this.clientName}/${this.serverId}/${clientId}`;
44
+ }
45
+ clientInfoKey(clientId) {
46
+ return `${this.keyPrefix(clientId)}/client_info/`;
47
+ }
48
+ async clientInformation() {
49
+ if (!this._clientId_) return;
50
+ return await this.storage.get(this.clientInfoKey(this.clientId)) ?? void 0;
51
+ }
52
+ async saveClientInformation(clientInformation) {
53
+ await this.storage.put(this.clientInfoKey(clientInformation.client_id), clientInformation);
54
+ this.clientId = clientInformation.client_id;
55
+ }
56
+ tokenKey(clientId) {
57
+ return `${this.keyPrefix(clientId)}/token`;
58
+ }
59
+ async tokens() {
60
+ if (!this._clientId_) return;
61
+ return await this.storage.get(this.tokenKey(this.clientId)) ?? void 0;
62
+ }
63
+ async saveTokens(tokens) {
64
+ await this.storage.put(this.tokenKey(this.clientId), tokens);
65
+ }
66
+ get authUrl() {
67
+ return this._authUrl_;
68
+ }
69
+ stateKey(nonce) {
70
+ return `/${this.clientName}/${this.serverId}/state/${nonce}`;
71
+ }
72
+ async state() {
73
+ const nonce = nanoid();
74
+ const state = `${nonce}.${this.serverId}`;
75
+ const storedState = {
76
+ nonce,
77
+ serverId: this.serverId,
78
+ createdAt: Date.now()
79
+ };
80
+ await this.storage.put(this.stateKey(nonce), storedState);
81
+ return state;
82
+ }
83
+ async checkState(state) {
84
+ const parts = state.split(".");
85
+ if (parts.length !== 2) return {
86
+ valid: false,
87
+ error: "Invalid state format"
88
+ };
89
+ const [nonce, serverId] = parts;
90
+ const key = this.stateKey(nonce);
91
+ const storedState = await this.storage.get(key);
92
+ if (!storedState) return {
93
+ valid: false,
94
+ error: "State not found or already used"
95
+ };
96
+ if (storedState.serverId !== serverId) {
97
+ await this.storage.delete(key);
98
+ return {
99
+ valid: false,
100
+ error: "State serverId mismatch"
101
+ };
102
+ }
103
+ if (Date.now() - storedState.createdAt > STATE_EXPIRATION_MS) {
104
+ await this.storage.delete(key);
105
+ return {
106
+ valid: false,
107
+ error: "State expired"
108
+ };
109
+ }
110
+ return {
111
+ valid: true,
112
+ serverId
113
+ };
114
+ }
115
+ async consumeState(state) {
116
+ const parts = state.split(".");
117
+ if (parts.length !== 2) {
118
+ console.warn(`[OAuth] consumeState called with invalid state format: ${state.substring(0, 20)}...`);
119
+ return;
120
+ }
121
+ const [nonce] = parts;
122
+ await this.storage.delete(this.stateKey(nonce));
123
+ }
124
+ async redirectToAuthorization(authUrl) {
125
+ this._authUrl_ = authUrl.toString();
126
+ }
127
+ async invalidateCredentials(scope) {
128
+ if (!this._clientId_) return;
129
+ const deleteKeys = [];
130
+ if (scope === "all" || scope === "client") deleteKeys.push(this.clientInfoKey(this.clientId));
131
+ if (scope === "all" || scope === "tokens") deleteKeys.push(this.tokenKey(this.clientId));
132
+ if (scope === "all" || scope === "verifier") deleteKeys.push(this.codeVerifierKey(this.clientId));
133
+ if (deleteKeys.length > 0) await this.storage.delete(deleteKeys);
134
+ }
135
+ codeVerifierKey(clientId) {
136
+ return `${this.keyPrefix(clientId)}/code_verifier`;
137
+ }
138
+ async saveCodeVerifier(verifier) {
139
+ const key = this.codeVerifierKey(this.clientId);
140
+ if (await this.storage.get(key)) return;
141
+ await this.storage.put(key, verifier);
142
+ }
143
+ async codeVerifier() {
144
+ const codeVerifier = await this.storage.get(this.codeVerifierKey(this.clientId));
145
+ if (!codeVerifier) throw new Error("No code verifier found");
146
+ return codeVerifier;
147
+ }
148
+ async deleteCodeVerifier() {
149
+ await this.storage.delete(this.codeVerifierKey(this.clientId));
150
+ }
151
+ };
152
+
153
+ //#endregion
154
+ export { DurableObjectOAuthClientProvider as t };
155
+ //# sourceMappingURL=do-oauth-client-provider-B1fVIshX.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"do-oauth-client-provider-B1fVIshX.js","names":["storage: DurableObjectStorage","clientName: string","baseRedirectUrl: string","storedState: StoredState","deleteKeys: string[]"],"sources":["../src/mcp/do-oauth-client-provider.ts"],"sourcesContent":["import type { OAuthClientProvider } from \"@modelcontextprotocol/sdk/client/auth.js\";\nimport type {\n OAuthClientInformation,\n OAuthClientInformationFull,\n OAuthClientMetadata,\n OAuthTokens\n} from \"@modelcontextprotocol/sdk/shared/auth.js\";\nimport { nanoid } from \"nanoid\";\n\nconst STATE_EXPIRATION_MS = 10 * 60 * 1000; // 10 minutes\n\ninterface StoredState {\n nonce: string;\n serverId: string;\n createdAt: number;\n}\n\n// A slight extension to the standard OAuthClientProvider interface because `redirectToAuthorization` doesn't give us the interface we need\n// This allows us to track authentication for a specific server and associated dynamic client registration\nexport interface AgentsOAuthProvider extends OAuthClientProvider {\n authUrl: string | undefined;\n clientId: string | undefined;\n serverId: string | undefined;\n checkState(\n state: string\n ): Promise<{ valid: boolean; serverId?: string; error?: string }>;\n consumeState(state: string): Promise<void>;\n deleteCodeVerifier(): Promise<void>;\n}\n\nexport class DurableObjectOAuthClientProvider implements AgentsOAuthProvider {\n private _authUrl_: string | undefined;\n private _serverId_: string | undefined;\n private _clientId_: string | undefined;\n\n constructor(\n public storage: DurableObjectStorage,\n public clientName: string,\n public baseRedirectUrl: string\n ) {\n if (!storage) {\n throw new Error(\n \"DurableObjectOAuthClientProvider requires a valid DurableObjectStorage instance\"\n );\n }\n }\n\n get clientMetadata(): OAuthClientMetadata {\n return {\n client_name: this.clientName,\n client_uri: this.clientUri,\n grant_types: [\"authorization_code\", \"refresh_token\"],\n redirect_uris: [this.redirectUrl],\n response_types: [\"code\"],\n token_endpoint_auth_method: \"none\"\n };\n }\n\n get clientUri() {\n return new URL(this.redirectUrl).origin;\n }\n\n get redirectUrl() {\n return this.baseRedirectUrl;\n }\n\n get clientId() {\n if (!this._clientId_) {\n throw new Error(\"Trying to access clientId before it was set\");\n }\n return this._clientId_;\n }\n\n set clientId(clientId_: string) {\n this._clientId_ = clientId_;\n }\n\n get serverId() {\n if (!this._serverId_) {\n throw new Error(\"Trying to access serverId before it was set\");\n }\n return this._serverId_;\n }\n\n set serverId(serverId_: string) {\n this._serverId_ = serverId_;\n }\n\n keyPrefix(clientId: string) {\n return `/${this.clientName}/${this.serverId}/${clientId}`;\n }\n\n clientInfoKey(clientId: string) {\n return `${this.keyPrefix(clientId)}/client_info/`;\n }\n\n async clientInformation(): Promise<OAuthClientInformation | undefined> {\n if (!this._clientId_) {\n return undefined;\n }\n return (\n (await this.storage.get<OAuthClientInformation>(\n this.clientInfoKey(this.clientId)\n )) ?? undefined\n );\n }\n\n async saveClientInformation(\n clientInformation: OAuthClientInformationFull\n ): Promise<void> {\n await this.storage.put(\n this.clientInfoKey(clientInformation.client_id),\n clientInformation\n );\n this.clientId = clientInformation.client_id;\n }\n\n tokenKey(clientId: string) {\n return `${this.keyPrefix(clientId)}/token`;\n }\n\n async tokens(): Promise<OAuthTokens | undefined> {\n if (!this._clientId_) {\n return undefined;\n }\n return (\n (await this.storage.get<OAuthTokens>(this.tokenKey(this.clientId))) ??\n undefined\n );\n }\n\n async saveTokens(tokens: OAuthTokens): Promise<void> {\n await this.storage.put(this.tokenKey(this.clientId), tokens);\n }\n\n get authUrl() {\n return this._authUrl_;\n }\n\n stateKey(nonce: string) {\n return `/${this.clientName}/${this.serverId}/state/${nonce}`;\n }\n\n async state(): Promise<string> {\n const nonce = nanoid();\n const state = `${nonce}.${this.serverId}`;\n const storedState: StoredState = {\n nonce,\n serverId: this.serverId,\n createdAt: Date.now()\n };\n await this.storage.put(this.stateKey(nonce), storedState);\n return state;\n }\n\n async checkState(\n state: string\n ): Promise<{ valid: boolean; serverId?: string; error?: string }> {\n const parts = state.split(\".\");\n if (parts.length !== 2) {\n return { valid: false, error: \"Invalid state format\" };\n }\n\n const [nonce, serverId] = parts;\n const key = this.stateKey(nonce);\n const storedState = await this.storage.get<StoredState>(key);\n\n if (!storedState) {\n return { valid: false, error: \"State not found or already used\" };\n }\n\n if (storedState.serverId !== serverId) {\n await this.storage.delete(key);\n return { valid: false, error: \"State serverId mismatch\" };\n }\n\n const age = Date.now() - storedState.createdAt;\n if (age > STATE_EXPIRATION_MS) {\n await this.storage.delete(key);\n return { valid: false, error: \"State expired\" };\n }\n\n return { valid: true, serverId };\n }\n\n async consumeState(state: string): Promise<void> {\n const parts = state.split(\".\");\n if (parts.length !== 2) {\n // This should never happen since checkState validates format first.\n // Log for debugging but don't throw - state consumption is best-effort.\n console.warn(\n `[OAuth] consumeState called with invalid state format: ${state.substring(0, 20)}...`\n );\n return;\n }\n const [nonce] = parts;\n await this.storage.delete(this.stateKey(nonce));\n }\n\n async redirectToAuthorization(authUrl: URL): Promise<void> {\n this._authUrl_ = authUrl.toString();\n }\n\n async invalidateCredentials(\n scope: \"all\" | \"client\" | \"tokens\" | \"verifier\"\n ): Promise<void> {\n if (!this._clientId_) return;\n\n const deleteKeys: string[] = [];\n\n if (scope === \"all\" || scope === \"client\") {\n deleteKeys.push(this.clientInfoKey(this.clientId));\n }\n if (scope === \"all\" || scope === \"tokens\") {\n deleteKeys.push(this.tokenKey(this.clientId));\n }\n if (scope === \"all\" || scope === \"verifier\") {\n deleteKeys.push(this.codeVerifierKey(this.clientId));\n }\n\n if (deleteKeys.length > 0) {\n await this.storage.delete(deleteKeys);\n }\n }\n\n codeVerifierKey(clientId: string) {\n return `${this.keyPrefix(clientId)}/code_verifier`;\n }\n\n async saveCodeVerifier(verifier: string): Promise<void> {\n const key = this.codeVerifierKey(this.clientId);\n\n // Don't overwrite existing verifier to preserve first PKCE verifier\n const existing = await this.storage.get<string>(key);\n if (existing) {\n return;\n }\n\n await this.storage.put(key, verifier);\n }\n\n async codeVerifier(): Promise<string> {\n const codeVerifier = await this.storage.get<string>(\n this.codeVerifierKey(this.clientId)\n );\n if (!codeVerifier) {\n throw new Error(\"No code verifier found\");\n }\n return codeVerifier;\n }\n\n async deleteCodeVerifier(): Promise<void> {\n await this.storage.delete(this.codeVerifierKey(this.clientId));\n }\n}\n"],"mappings":";;;AASA,MAAM,sBAAsB,MAAU;AAqBtC,IAAa,mCAAb,MAA6E;CAK3E,YACE,AAAOA,SACP,AAAOC,YACP,AAAOC,iBACP;EAHO;EACA;EACA;AAEP,MAAI,CAAC,QACH,OAAM,IAAI,MACR,kFACD;;CAIL,IAAI,iBAAsC;AACxC,SAAO;GACL,aAAa,KAAK;GAClB,YAAY,KAAK;GACjB,aAAa,CAAC,sBAAsB,gBAAgB;GACpD,eAAe,CAAC,KAAK,YAAY;GACjC,gBAAgB,CAAC,OAAO;GACxB,4BAA4B;GAC7B;;CAGH,IAAI,YAAY;AACd,SAAO,IAAI,IAAI,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B,YAAW,KAAK,KAAK,SAAS,KAAK,SAAS,CAAC;AAE/C,MAAI,UAAU,SAAS,UAAU,WAC/B,YAAW,KAAK,KAAK,gBAAgB,KAAK,SAAS,CAAC;AAGtD,MAAI,WAAW,SAAS,EACtB,OAAM,KAAK,QAAQ,OAAO,WAAW;;CAIzC,gBAAgB,UAAkB;AAChC,SAAO,GAAG,KAAK,UAAU,SAAS,CAAC;;CAGrC,MAAM,iBAAiB,UAAiC;EACtD,MAAM,MAAM,KAAK,gBAAgB,KAAK,SAAS;AAI/C,MADiB,MAAM,KAAK,QAAQ,IAAY,IAAI,CAElD;AAGF,QAAM,KAAK,QAAQ,IAAI,KAAK,SAAS;;CAGvC,MAAM,eAAgC;EACpC,MAAM,eAAe,MAAM,KAAK,QAAQ,IACtC,KAAK,gBAAgB,KAAK,SAAS,CACpC;AACD,MAAI,CAAC,aACH,OAAM,IAAI,MAAM,yBAAyB;AAE3C,SAAO;;CAGT,MAAM,qBAAoC;AACxC,QAAM,KAAK,QAAQ,OAAO,KAAK,gBAAgB,KAAK,SAAS,CAAC"}
@@ -1,87 +1,28 @@
1
+ import { n as AgentEmail } from "./context-DcbQ8o7k.js";
2
+ import {
3
+ h as TransportType,
4
+ t as MCPClientManager,
5
+ u as MCPConnectionState
6
+ } from "./client-BINtT7y-.js";
7
+ import { t as Observability } from "./index-DLuxm_9W.js";
8
+ import { n as MessageType } from "./ai-types-0OnT3FHg.js";
9
+ import {
10
+ Connection,
11
+ Connection as Connection$1,
12
+ ConnectionContext,
13
+ PartyServerOptions,
14
+ Server,
15
+ WSMessage
16
+ } from "partyserver";
1
17
  import { Client } from "@modelcontextprotocol/sdk/client/index.js";
2
18
  import {
3
- ServerCapabilities,
4
- Tool,
5
19
  Prompt,
6
- Resource
20
+ Resource,
21
+ ServerCapabilities,
22
+ Tool
7
23
  } from "@modelcontextprotocol/sdk/types.js";
8
- import { Server, Connection, PartyServerOptions } from "partyserver";
9
- import { MCPClientManager } from "./mcp/client.js";
10
- import { Message } from "ai";
11
24
 
12
- type BaseEvent<
13
- T extends string,
14
- Payload extends Record<string, unknown> = {}
15
- > = {
16
- type: T;
17
- /**
18
- * The unique identifier for the event
19
- */
20
- id: string;
21
- /**
22
- * The message to display in the logs for this event, should the implementation choose to display
23
- * a human-readable message.
24
- */
25
- displayMessage: string;
26
- /**
27
- * The payload of the event
28
- */
29
- payload: Payload;
30
- /**
31
- * The timestamp of the event in milliseconds since epoch
32
- */
33
- timestamp: number;
34
- };
35
- /**
36
- * The type of events that can be emitted by an Agent
37
- */
38
- type ObservabilityEvent =
39
- | BaseEvent<
40
- "state:update",
41
- {
42
- state: unknown;
43
- previousState: unknown;
44
- }
45
- >
46
- | BaseEvent<
47
- "rpc",
48
- {
49
- method: string;
50
- args: unknown[];
51
- streaming?: boolean;
52
- success: boolean;
53
- }
54
- >
55
- | BaseEvent<
56
- "message:request" | "message:response",
57
- {
58
- message: Message[];
59
- }
60
- >
61
- | BaseEvent<"message:clear">
62
- | BaseEvent<
63
- "schedule:create" | "schedule:execute" | "schedule:cancel",
64
- Schedule<unknown>
65
- >
66
- | BaseEvent<"destroy">
67
- | BaseEvent<
68
- "connect",
69
- {
70
- connectionId: string;
71
- }
72
- >;
73
- interface Observability {
74
- /**
75
- * Emit an event for the Agent's observability implementation to handle.
76
- * @param event - The event to emit
77
- * @param ctx - The execution context of the invocation
78
- */
79
- emit(event: ObservabilityEvent, ctx: DurableObjectState): void;
80
- }
81
- /**
82
- * A generic observability implementation that logs events to the console.
83
- */
84
- declare const genericObservability: Observability;
25
+ //#region src/index.d.ts
85
26
 
86
27
  /**
87
28
  * RPC request message from client
@@ -96,14 +37,14 @@ type RPCRequest = {
96
37
  * State update message from client
97
38
  */
98
39
  type StateUpdateMessage = {
99
- type: "cf_agent_state";
40
+ type: MessageType.CF_AGENT_STATE;
100
41
  state: unknown;
101
42
  };
102
43
  /**
103
44
  * RPC response message to client
104
45
  */
105
46
  type RPCResponse = {
106
- type: "rpc";
47
+ type: MessageType.RPC;
107
48
  id: string;
108
49
  } & (
109
50
  | {
@@ -134,16 +75,22 @@ type CallableMetadata = {
134
75
  * Decorator that marks a method as callable by clients
135
76
  * @param metadata Optional metadata about the callable method
136
77
  */
137
- declare function unstable_callable(
78
+ declare function callable(
138
79
  metadata?: CallableMetadata
139
80
  ): <This, Args extends unknown[], Return>(
140
81
  target: (this: This, ...args: Args) => Return,
141
82
  context: ClassMethodDecoratorContext
142
83
  ) => (this: This, ...args: Args) => Return;
84
+ /**
85
+ * Decorator that marks a method as callable by clients
86
+ * @deprecated this has been renamed to callable, and unstable_callable will be removed in the next major version
87
+ * @param metadata Optional metadata about the callable method
88
+ */
89
+ declare const unstable_callable: (metadata?: CallableMetadata) => void;
143
90
  type QueueItem<T = string> = {
144
91
  id: string;
145
92
  payload: T;
146
- callback: keyof Agent<unknown>;
93
+ callback: keyof Agent<Cloudflare.Env>;
147
94
  created_at: number;
148
95
  };
149
96
  /**
@@ -185,27 +132,33 @@ type Schedule<T = string> = {
185
132
  * MCP Server state update message from server -> Client
186
133
  */
187
134
  type MCPServerMessage = {
188
- type: "cf_agent_mcp_servers";
135
+ type: MessageType.CF_AGENT_MCP_SERVERS;
189
136
  mcp: MCPServersState;
190
137
  };
191
138
  type MCPServersState = {
192
139
  servers: {
193
140
  [id: string]: MCPServer;
194
141
  };
195
- tools: Tool[];
196
- prompts: Prompt[];
197
- resources: Resource[];
142
+ tools: (Tool & {
143
+ serverId: string;
144
+ })[];
145
+ prompts: (Prompt & {
146
+ serverId: string;
147
+ })[];
148
+ resources: (Resource & {
149
+ serverId: string;
150
+ })[];
198
151
  };
199
152
  type MCPServer = {
200
153
  name: string;
201
154
  server_url: string;
202
155
  auth_url: string | null;
203
- state: "authenticating" | "connecting" | "ready" | "discovering" | "failed";
156
+ state: MCPConnectionState;
204
157
  instructions: string | null;
205
158
  capabilities: ServerCapabilities | null;
206
159
  };
207
160
  declare function getCurrentAgent<
208
- T extends Agent<unknown, unknown> = Agent<unknown, unknown>
161
+ T extends Agent<Cloudflare.Env> = Agent<Cloudflare.Env>
209
162
  >(): {
210
163
  agent: T | undefined;
211
164
  connection: Connection | undefined;
@@ -217,10 +170,16 @@ declare function getCurrentAgent<
217
170
  * @template Env Environment type containing bindings
218
171
  * @template State State type to store within the Agent
219
172
  */
220
- declare class Agent<Env, State = unknown> extends Server<Env> {
173
+ declare class Agent<
174
+ Env extends Cloudflare.Env = Cloudflare.Env,
175
+ State = unknown,
176
+ Props extends Record<string, unknown> = Record<string, unknown>
177
+ > extends Server<Env, Props> {
221
178
  private _state;
179
+ private _disposables;
180
+ private _destroyed;
222
181
  private _ParentClass;
223
- mcp: MCPClientManager;
182
+ readonly mcp: MCPClientManager;
224
183
  /**
225
184
  * Initial state for the Agent
226
185
  * Override to provide default state values
@@ -372,7 +331,7 @@ declare class Agent<Env, State = unknown> extends Server<Env> {
372
331
  /**
373
332
  * Cancel a scheduled task
374
333
  * @param id ID of the task to cancel
375
- * @returns true if the task was cancelled, false otherwise
334
+ * @returns true if the task was cancelled, false if the task was not found
376
335
  */
377
336
  cancelSchedule(id: string): Promise<boolean>;
378
337
  private _scheduleNextAlarm;
@@ -397,61 +356,69 @@ declare class Agent<Env, State = unknown> extends Server<Env> {
397
356
  /**
398
357
  * Connect to a new MCP Server
399
358
  *
359
+ * @param serverName Name of the MCP server
400
360
  * @param url MCP Server SSE URL
401
- * @param callbackHost Base host for the agent, used for the redirect URI.
361
+ * @param callbackHost Base host for the agent, used for the redirect URI. If not provided, will be derived from the current request.
402
362
  * @param agentsPrefix agents routing prefix if not using `agents`
403
- * @param options MCP client and transport (header) options
404
- * @returns authUrl
363
+ * @param options MCP client and transport options
364
+ * @returns Server id and state - either "authenticating" with authUrl, or "ready"
365
+ * @throws If connection or discovery fails
405
366
  */
406
367
  addMcpServer(
407
368
  serverName: string,
408
369
  url: string,
409
- callbackHost: string,
370
+ callbackHost?: string,
410
371
  agentsPrefix?: string,
411
372
  options?: {
412
373
  client?: ConstructorParameters<typeof Client>[1];
413
- transport?: {
414
- headers: HeadersInit;
415
- };
416
- }
417
- ): Promise<{
418
- id: string;
419
- authUrl: string | undefined;
420
- }>;
421
- _connectToMcpServerInternal(
422
- _serverName: string,
423
- url: string,
424
- callbackUrl: string,
425
- options?: {
426
- client?: ConstructorParameters<typeof Client>[1];
427
- /**
428
- * We don't expose the normal set of transport options because:
429
- * 1) we can't serialize things like the auth provider or a fetch function into the DB for reconnection purposes
430
- * 2) We probably want these options to be agnostic to the transport type (SSE vs Streamable)
431
- *
432
- * This has the limitation that you can't override fetch, but I think headers should handle nearly all cases needed (i.e. non-standard bearer auth).
433
- */
434
374
  transport?: {
435
375
  headers?: HeadersInit;
376
+ type?: TransportType;
436
377
  };
437
- },
438
- reconnect?: {
439
- id: string;
440
- oauthClientId?: string;
441
378
  }
442
- ): Promise<{
443
- id: string;
444
- authUrl: string | undefined;
445
- clientId: string | undefined;
446
- }>;
379
+ ): Promise<
380
+ | {
381
+ id: string;
382
+ state: typeof MCPConnectionState.AUTHENTICATING;
383
+ authUrl: string;
384
+ }
385
+ | {
386
+ id: string;
387
+ state: typeof MCPConnectionState.READY;
388
+ authUrl?: undefined;
389
+ }
390
+ >;
447
391
  removeMcpServer(id: string): Promise<void>;
448
392
  getMcpServers(): MCPServersState;
393
+ private broadcastMcpServers;
394
+ /**
395
+ * Handle MCP OAuth callback request if it's an OAuth callback.
396
+ *
397
+ * This method encapsulates the entire OAuth callback flow:
398
+ * 1. Checks if the request is an MCP OAuth callback
399
+ * 2. Processes the OAuth code exchange
400
+ * 3. Establishes the connection if successful
401
+ * 4. Broadcasts MCP server state updates
402
+ * 5. Returns the appropriate HTTP response
403
+ *
404
+ * @param request The incoming HTTP request
405
+ * @returns Response if this was an OAuth callback, null otherwise
406
+ */
407
+ private handleMcpOAuthCallback;
408
+ /**
409
+ * Handle OAuth callback response using MCPClientManager configuration
410
+ * @param result OAuth callback result
411
+ * @param request The original request (needed for base URL)
412
+ * @returns Response for the OAuth callback
413
+ */
414
+ private handleOAuthCallbackResponse;
449
415
  }
450
416
  /**
451
417
  * Namespace for creating Agent instances
452
418
  * @template Agentic Type of the Agent class
419
+ * @deprecated Use DurableObjectNamespace instead
453
420
  */
454
- type AgentNamespace<Agentic extends Agent<unknown>> =
421
+ type AgentNamespace<Agentic extends Agent<Cloudflare.Env>> =
455
422
  DurableObjectNamespace<Agentic>;
456
423
  /**
457
424
  * Agent's durable context
@@ -518,21 +485,11 @@ type EmailRoutingOptions<Env> = AgentOptions<Env> & {
518
485
  * @param options The options for routing the email
519
486
  * @returns A promise that resolves when the email has been routed
520
487
  */
521
- declare function routeAgentEmail<Env>(
488
+ declare function routeAgentEmail<Env extends Cloudflare.Env = Cloudflare.Env>(
522
489
  email: ForwardableEmailMessage,
523
490
  env: Env,
524
491
  options: EmailRoutingOptions<Env>
525
492
  ): Promise<void>;
526
- type AgentEmail = {
527
- from: string;
528
- to: string;
529
- getRaw: () => Promise<Uint8Array>;
530
- headers: Headers;
531
- rawSize: number;
532
- setReject: (reason: string) => void;
533
- forward: (rcptTo: string, headers?: Headers) => Promise<void>;
534
- reply: (options: { from: string; to: string; raw: string }) => Promise<void>;
535
- };
536
493
  type EmailSendOptions = {
537
494
  to: string;
538
495
  subject: string;
@@ -553,12 +510,17 @@ type EmailSendOptions = {
553
510
  * @param options Options for Agent creation
554
511
  * @returns Promise resolving to an Agent instance stub
555
512
  */
556
- declare function getAgentByName<Env, T extends Agent<Env>>(
557
- namespace: AgentNamespace<T>,
513
+ declare function getAgentByName<
514
+ Env extends Cloudflare.Env = Cloudflare.Env,
515
+ T extends Agent<Env> = Agent<Env>,
516
+ Props extends Record<string, unknown> = Record<string, unknown>
517
+ >(
518
+ namespace: DurableObjectNamespace<T>,
558
519
  name: string,
559
520
  options?: {
560
521
  jurisdiction?: DurableObjectJurisdiction;
561
522
  locationHint?: DurableObjectLocationHint;
523
+ props?: Props;
562
524
  }
563
525
  ): Promise<DurableObjectStub<T>>;
564
526
  /**
@@ -580,35 +542,36 @@ declare class StreamingResponse {
580
542
  */
581
543
  end(finalChunk?: unknown): void;
582
544
  }
583
-
545
+ //#endregion
584
546
  export {
585
- Agent as A,
586
- type CallableMetadata as C,
587
- type EmailResolver as E,
588
- type MCPServersState as M,
589
- type ObservabilityEvent as O,
590
- type QueueItem as Q,
591
- type RPCRequest as R,
592
- type StateUpdateMessage as S,
593
- type AgentContext as a,
594
- type Observability as b,
595
- type RPCResponse as c,
596
- type Schedule as d,
597
- type MCPServerMessage as e,
598
- type MCPServer as f,
599
- genericObservability as g,
600
- getCurrentAgent as h,
601
- type AgentNamespace as i,
602
- type AgentOptions as j,
603
- createHeaderBasedEmailResolver as k,
604
- createAddressBasedEmailResolver as l,
605
- createCatchAllEmailResolver as m,
606
- type EmailRoutingOptions as n,
607
- routeAgentEmail as o,
608
- type AgentEmail as p,
609
- type EmailSendOptions as q,
610
- routeAgentRequest as r,
611
- getAgentByName as s,
612
- StreamingResponse as t,
613
- unstable_callable as u
547
+ createCatchAllEmailResolver as C,
548
+ routeAgentEmail as D,
549
+ getCurrentAgent as E,
550
+ routeAgentRequest as O,
551
+ createAddressBasedEmailResolver as S,
552
+ getAgentByName as T,
553
+ Schedule as _,
554
+ CallableMetadata as a,
555
+ WSMessage as b,
556
+ EmailResolver as c,
557
+ MCPServer as d,
558
+ MCPServerMessage as f,
559
+ RPCResponse as g,
560
+ RPCRequest as h,
561
+ AgentOptions as i,
562
+ unstable_callable as k,
563
+ EmailRoutingOptions as l,
564
+ QueueItem as m,
565
+ AgentContext as n,
566
+ Connection$1 as o,
567
+ MCPServersState as p,
568
+ AgentNamespace as r,
569
+ ConnectionContext as s,
570
+ Agent as t,
571
+ EmailSendOptions as u,
572
+ StateUpdateMessage as v,
573
+ createHeaderBasedEmailResolver as w,
574
+ callable as x,
575
+ StreamingResponse as y
614
576
  };
577
+ //# sourceMappingURL=index-CxZRDFxS.d.ts.map
@@ -0,0 +1,58 @@
1
+ import { n as BaseEvent, t as MCPObservabilityEvent } from "./mcp-CPSfGUgd.js";
2
+
3
+ //#region src/observability/agent.d.ts
4
+
5
+ /**
6
+ * Agent-specific observability events
7
+ * These track the lifecycle and operations of an Agent
8
+ */
9
+ type AgentObservabilityEvent =
10
+ | BaseEvent<"state:update", {}>
11
+ | BaseEvent<
12
+ "rpc",
13
+ {
14
+ method: string;
15
+ streaming?: boolean;
16
+ }
17
+ >
18
+ | BaseEvent<"message:request" | "message:response", {}>
19
+ | BaseEvent<"message:clear">
20
+ | BaseEvent<
21
+ "schedule:create" | "schedule:execute" | "schedule:cancel",
22
+ {
23
+ callback: string;
24
+ id: string;
25
+ }
26
+ >
27
+ | BaseEvent<"destroy">
28
+ | BaseEvent<
29
+ "connect",
30
+ {
31
+ connectionId: string;
32
+ }
33
+ >;
34
+ //#endregion
35
+ //#region src/observability/index.d.ts
36
+ /**
37
+ * Union of all observability event types from different domains
38
+ */
39
+ type ObservabilityEvent = AgentObservabilityEvent | MCPObservabilityEvent;
40
+ interface Observability {
41
+ /**
42
+ * Emit an event for the Agent's observability implementation to handle.
43
+ * @param event - The event to emit
44
+ * @param ctx - The execution context of the invocation (optional)
45
+ */
46
+ emit(event: ObservabilityEvent, ctx?: DurableObjectState): void;
47
+ }
48
+ /**
49
+ * A generic observability implementation that logs events to the console.
50
+ */
51
+ declare const genericObservability: Observability;
52
+ //#endregion
53
+ export {
54
+ ObservabilityEvent as n,
55
+ genericObservability as r,
56
+ Observability as t
57
+ };
58
+ //# sourceMappingURL=index-DLuxm_9W.d.ts.map