@yourgpt/copilot-sdk 2.0.1 → 2.0.2-beta.2

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 (215) hide show
  1. package/README.md +42 -0
  2. package/dist/{ThreadManager-JT0sqSSD.d.ts → ThreadManager-Dkp_eLty.d.ts} +1 -1
  3. package/dist/{ThreadManager-CUq5Ocu2.d.cts → ThreadManager-LfFRhr4e.d.cts} +1 -1
  4. package/dist/anthropic-6F5GRE3B.js +4 -0
  5. package/dist/anthropic-6F5GRE3B.js.map +1 -0
  6. package/dist/anthropic-DGalr_Fw.d.cts +17 -0
  7. package/dist/anthropic-DkCEDYOt.d.ts +17 -0
  8. package/dist/anthropic-NMTRABEH.cjs +21 -0
  9. package/dist/anthropic-NMTRABEH.cjs.map +1 -0
  10. package/dist/brave-DdnWb7Gb.d.cts +17 -0
  11. package/dist/brave-DsI9n7Wr.d.ts +17 -0
  12. package/dist/brave-OYKCOZEM.cjs +21 -0
  13. package/dist/brave-OYKCOZEM.cjs.map +1 -0
  14. package/dist/brave-XSASGGH2.js +4 -0
  15. package/dist/brave-XSASGGH2.js.map +1 -0
  16. package/dist/chunk-2FAWEBZS.cjs +88 -0
  17. package/dist/chunk-2FAWEBZS.cjs.map +1 -0
  18. package/dist/chunk-53UGJNHN.js +92 -0
  19. package/dist/chunk-53UGJNHN.js.map +1 -0
  20. package/dist/chunk-6T5XXJEP.cjs +80 -0
  21. package/dist/chunk-6T5XXJEP.cjs.map +1 -0
  22. package/dist/chunk-7K7HZMP4.cjs +1170 -0
  23. package/dist/chunk-7K7HZMP4.cjs.map +1 -0
  24. package/dist/chunk-7W7QLZNC.js +72 -0
  25. package/dist/chunk-7W7QLZNC.js.map +1 -0
  26. package/dist/{chunk-JM7PB2LP.js → chunk-7XFFRV7D.js} +10 -66
  27. package/dist/chunk-7XFFRV7D.js.map +1 -0
  28. package/dist/chunk-ASV6JLYG.cjs +99 -0
  29. package/dist/chunk-ASV6JLYG.cjs.map +1 -0
  30. package/dist/chunk-BH7MNDWW.js +1152 -0
  31. package/dist/chunk-BH7MNDWW.js.map +1 -0
  32. package/dist/chunk-BKO7DSPU.js +67 -0
  33. package/dist/chunk-BKO7DSPU.js.map +1 -0
  34. package/dist/chunk-CBAHCI4R.cjs +76 -0
  35. package/dist/chunk-CBAHCI4R.cjs.map +1 -0
  36. package/dist/chunk-CEKAYA2Q.cjs +74 -0
  37. package/dist/chunk-CEKAYA2Q.cjs.map +1 -0
  38. package/dist/chunk-CEOMTQTP.js +85 -0
  39. package/dist/chunk-CEOMTQTP.js.map +1 -0
  40. package/dist/chunk-DABZYCVX.js +84 -0
  41. package/dist/chunk-DABZYCVX.js.map +1 -0
  42. package/dist/chunk-DGUM43GV.js +10 -0
  43. package/dist/chunk-DGUM43GV.js.map +1 -0
  44. package/dist/chunk-G4SF2PNQ.js +33 -0
  45. package/dist/chunk-G4SF2PNQ.js.map +1 -0
  46. package/dist/chunk-GANCV72Z.cjs +110 -0
  47. package/dist/chunk-GANCV72Z.cjs.map +1 -0
  48. package/dist/{chunk-BLSI67J6.cjs → chunk-H5XMKBBA.cjs} +425 -30
  49. package/dist/chunk-H5XMKBBA.cjs.map +1 -0
  50. package/dist/{chunk-CJ7UWN2Y.js → chunk-IXFV6AW6.js} +397 -7
  51. package/dist/chunk-IXFV6AW6.js.map +1 -0
  52. package/dist/chunk-JEQ2X3Z6.cjs +12 -0
  53. package/dist/chunk-JEQ2X3Z6.cjs.map +1 -0
  54. package/dist/chunk-JO4BHPAD.cjs +40 -0
  55. package/dist/chunk-JO4BHPAD.cjs.map +1 -0
  56. package/dist/chunk-MEBXW75C.cjs +89 -0
  57. package/dist/chunk-MEBXW75C.cjs.map +1 -0
  58. package/dist/chunk-MNDGIW47.js +76 -0
  59. package/dist/chunk-MNDGIW47.js.map +1 -0
  60. package/dist/chunk-PPFHA6IL.js +83 -0
  61. package/dist/chunk-PPFHA6IL.js.map +1 -0
  62. package/dist/chunk-RQ74USYU.js +128 -0
  63. package/dist/chunk-RQ74USYU.js.map +1 -0
  64. package/dist/chunk-TXLIY7GF.cjs +132 -0
  65. package/dist/chunk-TXLIY7GF.cjs.map +1 -0
  66. package/dist/chunk-UIWFYMAO.cjs +82 -0
  67. package/dist/chunk-UIWFYMAO.cjs.map +1 -0
  68. package/dist/{chunk-4PRWNAXQ.cjs → chunk-UOWLKFXK.cjs} +27 -89
  69. package/dist/chunk-UOWLKFXK.cjs.map +1 -0
  70. package/dist/chunk-VD74IPKB.js +106 -0
  71. package/dist/chunk-VD74IPKB.js.map +1 -0
  72. package/dist/chunk-W73FBYIH.cjs +87 -0
  73. package/dist/chunk-W73FBYIH.cjs.map +1 -0
  74. package/dist/chunk-XGITAEXU.js +93 -0
  75. package/dist/chunk-XGITAEXU.js.map +1 -0
  76. package/dist/chunk-XWOHNY3F.cjs +96 -0
  77. package/dist/chunk-XWOHNY3F.cjs.map +1 -0
  78. package/dist/chunk-ZPYQDMUX.js +79 -0
  79. package/dist/chunk-ZPYQDMUX.js.map +1 -0
  80. package/dist/core/index.cjs +156 -84
  81. package/dist/core/index.d.cts +16 -4
  82. package/dist/core/index.d.ts +16 -4
  83. package/dist/core/index.js +13 -1
  84. package/dist/exa-72KFY5A7.cjs +21 -0
  85. package/dist/exa-72KFY5A7.cjs.map +1 -0
  86. package/dist/exa-Dp9U-WTc.d.ts +17 -0
  87. package/dist/exa-NNVPBC2M.js +4 -0
  88. package/dist/exa-NNVPBC2M.js.map +1 -0
  89. package/dist/exa-jJSPhyUW.d.cts +17 -0
  90. package/dist/google-CHU2yycE.d.cts +17 -0
  91. package/dist/google-CTEK6SV2.js +4 -0
  92. package/dist/google-CTEK6SV2.js.map +1 -0
  93. package/dist/google-Da8IQxaI.d.ts +17 -0
  94. package/dist/google-IIUXFFVF.cjs +21 -0
  95. package/dist/google-IIUXFFVF.cjs.map +1 -0
  96. package/dist/index-2VtgKM8S.d.cts +206 -0
  97. package/dist/index-pWEH7pUE.d.ts +206 -0
  98. package/dist/mcp/index.cjs +670 -0
  99. package/dist/mcp/index.cjs.map +1 -0
  100. package/dist/mcp/index.d.cts +779 -0
  101. package/dist/mcp/index.d.ts +779 -0
  102. package/dist/mcp/index.js +574 -0
  103. package/dist/mcp/index.js.map +1 -0
  104. package/dist/openai-6KTCQ7PZ.cjs +21 -0
  105. package/dist/openai-6KTCQ7PZ.cjs.map +1 -0
  106. package/dist/openai-7W2PCNW5.js +4 -0
  107. package/dist/openai-7W2PCNW5.js.map +1 -0
  108. package/dist/openai-Cam8hF4f.d.ts +17 -0
  109. package/dist/openai-HVSCuXgO.d.cts +17 -0
  110. package/dist/react/index.cjs +75 -42
  111. package/dist/react/index.d.cts +270 -45
  112. package/dist/react/index.d.ts +270 -45
  113. package/dist/react/index.js +15 -2
  114. package/dist/searxng-AXLVGY7Z.js +4 -0
  115. package/dist/searxng-AXLVGY7Z.js.map +1 -0
  116. package/dist/searxng-EJKNY236.cjs +21 -0
  117. package/dist/searxng-EJKNY236.cjs.map +1 -0
  118. package/dist/searxng-K0qtY9vp.d.ts +17 -0
  119. package/dist/searxng-QGOte_Gq.d.cts +17 -0
  120. package/dist/serper-3JYJHJX6.js +4 -0
  121. package/dist/serper-3JYJHJX6.js.map +1 -0
  122. package/dist/serper-63FT4AOL.cjs +21 -0
  123. package/dist/serper-63FT4AOL.cjs.map +1 -0
  124. package/dist/serper-7Czya3PW.d.ts +17 -0
  125. package/dist/serper-JzdaSnS9.d.cts +17 -0
  126. package/dist/styles.css +38 -0
  127. package/dist/tavily-AWFP4RM7.cjs +21 -0
  128. package/dist/tavily-AWFP4RM7.cjs.map +1 -0
  129. package/dist/tavily-C8cXXojE.d.cts +17 -0
  130. package/dist/tavily-CIWAAZPH.js +4 -0
  131. package/dist/tavily-CIWAAZPH.js.map +1 -0
  132. package/dist/tavily-DdSGVgkE.d.ts +17 -0
  133. package/dist/themes/catppuccin.css +2 -0
  134. package/dist/themes/claude.css +2 -0
  135. package/dist/themes/linear.css +2 -0
  136. package/dist/themes/modern-minimal.css +2 -0
  137. package/dist/themes/posthog.css +2 -0
  138. package/dist/themes/supabase.css +2 -0
  139. package/dist/themes/twitter.css +2 -0
  140. package/dist/themes/vercel.css +2 -0
  141. package/dist/tools/anthropic/index.cjs +61 -0
  142. package/dist/tools/anthropic/index.cjs.map +1 -0
  143. package/dist/tools/anthropic/index.d.cts +67 -0
  144. package/dist/tools/anthropic/index.d.ts +67 -0
  145. package/dist/tools/anthropic/index.js +56 -0
  146. package/dist/tools/anthropic/index.js.map +1 -0
  147. package/dist/tools/brave/index.cjs +85 -0
  148. package/dist/tools/brave/index.cjs.map +1 -0
  149. package/dist/tools/brave/index.d.cts +91 -0
  150. package/dist/tools/brave/index.d.ts +91 -0
  151. package/dist/tools/brave/index.js +80 -0
  152. package/dist/tools/brave/index.js.map +1 -0
  153. package/dist/tools/exa/index.cjs +90 -0
  154. package/dist/tools/exa/index.cjs.map +1 -0
  155. package/dist/tools/exa/index.d.cts +92 -0
  156. package/dist/tools/exa/index.d.ts +92 -0
  157. package/dist/tools/exa/index.js +85 -0
  158. package/dist/tools/exa/index.js.map +1 -0
  159. package/dist/tools/google/index.cjs +81 -0
  160. package/dist/tools/google/index.cjs.map +1 -0
  161. package/dist/tools/google/index.d.cts +81 -0
  162. package/dist/tools/google/index.d.ts +81 -0
  163. package/dist/tools/google/index.js +76 -0
  164. package/dist/tools/google/index.js.map +1 -0
  165. package/dist/tools/openai/index.cjs +83 -0
  166. package/dist/tools/openai/index.cjs.map +1 -0
  167. package/dist/tools/openai/index.d.cts +84 -0
  168. package/dist/tools/openai/index.d.ts +84 -0
  169. package/dist/tools/openai/index.js +78 -0
  170. package/dist/tools/openai/index.js.map +1 -0
  171. package/dist/tools/searxng/index.cjs +85 -0
  172. package/dist/tools/searxng/index.cjs.map +1 -0
  173. package/dist/tools/searxng/index.d.cts +91 -0
  174. package/dist/tools/searxng/index.d.ts +91 -0
  175. package/dist/tools/searxng/index.js +80 -0
  176. package/dist/tools/searxng/index.js.map +1 -0
  177. package/dist/tools/serper/index.cjs +85 -0
  178. package/dist/tools/serper/index.cjs.map +1 -0
  179. package/dist/tools/serper/index.d.cts +91 -0
  180. package/dist/tools/serper/index.d.ts +91 -0
  181. package/dist/tools/serper/index.js +80 -0
  182. package/dist/tools/serper/index.js.map +1 -0
  183. package/dist/tools/tavily/index.cjs +91 -0
  184. package/dist/tools/tavily/index.cjs.map +1 -0
  185. package/dist/tools/tavily/index.d.cts +95 -0
  186. package/dist/tools/tavily/index.d.ts +95 -0
  187. package/dist/tools/tavily/index.js +86 -0
  188. package/dist/tools/tavily/index.js.map +1 -0
  189. package/dist/tools/web-search/index.cjs +31 -0
  190. package/dist/tools/web-search/index.cjs.map +1 -0
  191. package/dist/tools/web-search/index.d.cts +3 -0
  192. package/dist/tools/web-search/index.d.ts +3 -0
  193. package/dist/tools/web-search/index.js +14 -0
  194. package/dist/tools/web-search/index.js.map +1 -0
  195. package/dist/{types-BtAaOV07.d.cts → tools-DDWrco4h.d.cts} +43 -367
  196. package/dist/{types-BtAaOV07.d.ts → tools-DDWrco4h.d.ts} +43 -367
  197. package/dist/types-B20VCJXL.d.cts +347 -0
  198. package/dist/types-B20VCJXL.d.ts +347 -0
  199. package/dist/types-Cizh9K_f.d.ts +441 -0
  200. package/dist/types-DG2ya08y.d.cts +367 -0
  201. package/dist/types-DG2ya08y.d.ts +367 -0
  202. package/dist/types-DjSfYNKj.d.cts +441 -0
  203. package/dist/types-ZguuKEs_.d.cts +127 -0
  204. package/dist/types-ZguuKEs_.d.ts +127 -0
  205. package/dist/ui/index.cjs +1075 -148
  206. package/dist/ui/index.cjs.map +1 -1
  207. package/dist/ui/index.d.cts +410 -4
  208. package/dist/ui/index.d.ts +410 -4
  209. package/dist/ui/index.js +1007 -96
  210. package/dist/ui/index.js.map +1 -1
  211. package/package.json +52 -2
  212. package/dist/chunk-4PRWNAXQ.cjs.map +0 -1
  213. package/dist/chunk-BLSI67J6.cjs.map +0 -1
  214. package/dist/chunk-CJ7UWN2Y.js.map +0 -1
  215. package/dist/chunk-JM7PB2LP.js.map +0 -1
@@ -0,0 +1,1152 @@
1
+ // src/mcp/types.ts
2
+ var JSON_RPC_ERROR_CODES = {
3
+ PARSE_ERROR: -32700,
4
+ INVALID_REQUEST: -32600,
5
+ METHOD_NOT_FOUND: -32601,
6
+ INVALID_PARAMS: -32602,
7
+ INTERNAL_ERROR: -32603
8
+ };
9
+ var MCP_PROTOCOL_VERSION = "2025-06-18";
10
+ var MCPError = class _MCPError extends Error {
11
+ constructor(message, code, data) {
12
+ super(message);
13
+ this.code = code;
14
+ this.data = data;
15
+ this.name = "MCPError";
16
+ }
17
+ static fromJsonRpcError(error) {
18
+ return new _MCPError(error.message, error.code, error.data);
19
+ }
20
+ };
21
+
22
+ // src/mcp/protocol/JsonRpcHandler.ts
23
+ var JsonRpcHandler = class {
24
+ constructor(options) {
25
+ this.requestId = 0;
26
+ this.pendingRequests = /* @__PURE__ */ new Map();
27
+ this.defaultTimeout = options?.timeout ?? 3e4;
28
+ }
29
+ /**
30
+ * Generate a unique request ID
31
+ */
32
+ generateId() {
33
+ return `req_${++this.requestId}_${Date.now()}`;
34
+ }
35
+ /**
36
+ * Create a JSON-RPC request
37
+ */
38
+ createRequest(method, params) {
39
+ const request = {
40
+ jsonrpc: "2.0",
41
+ id: this.generateId(),
42
+ method
43
+ };
44
+ if (params !== void 0) {
45
+ request.params = params;
46
+ }
47
+ return request;
48
+ }
49
+ /**
50
+ * Create a JSON-RPC notification (no response expected)
51
+ */
52
+ createNotification(method, params) {
53
+ const notification = {
54
+ jsonrpc: "2.0",
55
+ method
56
+ };
57
+ if (params !== void 0) {
58
+ notification.params = params;
59
+ }
60
+ return notification;
61
+ }
62
+ /**
63
+ * Register a pending request and return a promise that resolves when response is received
64
+ */
65
+ registerRequest(request, timeout) {
66
+ return new Promise((resolve, reject) => {
67
+ const timeoutMs = timeout ?? this.defaultTimeout;
68
+ const timeoutHandle = setTimeout(() => {
69
+ this.pendingRequests.delete(request.id);
70
+ reject(
71
+ new MCPError(
72
+ `Request timed out after ${timeoutMs}ms: ${request.method}`,
73
+ JSON_RPC_ERROR_CODES.INTERNAL_ERROR
74
+ )
75
+ );
76
+ }, timeoutMs);
77
+ this.pendingRequests.set(request.id, {
78
+ resolve,
79
+ reject,
80
+ timeout: timeoutHandle
81
+ });
82
+ });
83
+ }
84
+ /**
85
+ * Handle an incoming JSON-RPC response
86
+ */
87
+ handleResponse(response) {
88
+ if (response.id === null) {
89
+ return false;
90
+ }
91
+ const pending = this.pendingRequests.get(response.id);
92
+ if (!pending) {
93
+ return false;
94
+ }
95
+ this.pendingRequests.delete(response.id);
96
+ clearTimeout(pending.timeout);
97
+ if (isErrorResponse(response)) {
98
+ pending.reject(MCPError.fromJsonRpcError(response.error));
99
+ } else {
100
+ pending.resolve(response.result);
101
+ }
102
+ return true;
103
+ }
104
+ /**
105
+ * Parse a JSON-RPC message from string
106
+ */
107
+ parse(data) {
108
+ try {
109
+ const parsed = JSON.parse(data);
110
+ if (!this.isValidMessage(parsed)) {
111
+ throw new MCPError(
112
+ "Invalid JSON-RPC message",
113
+ JSON_RPC_ERROR_CODES.INVALID_REQUEST
114
+ );
115
+ }
116
+ return parsed;
117
+ } catch (error) {
118
+ if (error instanceof MCPError) {
119
+ throw error;
120
+ }
121
+ throw new MCPError(
122
+ "Failed to parse JSON-RPC message",
123
+ JSON_RPC_ERROR_CODES.PARSE_ERROR,
124
+ error
125
+ );
126
+ }
127
+ }
128
+ /**
129
+ * Serialize a JSON-RPC message to string
130
+ */
131
+ serialize(message) {
132
+ return JSON.stringify(message);
133
+ }
134
+ /**
135
+ * Validate a JSON-RPC message
136
+ */
137
+ isValidMessage(message) {
138
+ if (!message || typeof message !== "object") {
139
+ return false;
140
+ }
141
+ const msg = message;
142
+ if (msg.jsonrpc !== "2.0") {
143
+ return false;
144
+ }
145
+ if ("method" in msg && typeof msg.method === "string") {
146
+ return true;
147
+ }
148
+ if ("id" in msg) {
149
+ return "result" in msg || "error" in msg;
150
+ }
151
+ return false;
152
+ }
153
+ /**
154
+ * Check if message is a request
155
+ */
156
+ isRequest(message) {
157
+ return "method" in message && "id" in message;
158
+ }
159
+ /**
160
+ * Check if message is a notification
161
+ */
162
+ isNotification(message) {
163
+ return "method" in message && !("id" in message);
164
+ }
165
+ /**
166
+ * Check if message is a response
167
+ */
168
+ isResponse(message) {
169
+ return "id" in message && ("result" in message || "error" in message);
170
+ }
171
+ /**
172
+ * Cancel all pending requests
173
+ */
174
+ cancelAllPending(reason) {
175
+ const error = new MCPError(
176
+ reason ?? "All pending requests cancelled",
177
+ JSON_RPC_ERROR_CODES.INTERNAL_ERROR
178
+ );
179
+ for (const [id, pending] of this.pendingRequests) {
180
+ clearTimeout(pending.timeout);
181
+ pending.reject(error);
182
+ }
183
+ this.pendingRequests.clear();
184
+ }
185
+ /**
186
+ * Get number of pending requests
187
+ */
188
+ getPendingCount() {
189
+ return this.pendingRequests.size;
190
+ }
191
+ /**
192
+ * Check if a specific request is pending
193
+ */
194
+ isPending(id) {
195
+ return this.pendingRequests.has(id);
196
+ }
197
+ };
198
+ function isErrorResponse(response) {
199
+ return "error" in response;
200
+ }
201
+
202
+ // src/mcp/protocol/messages.ts
203
+ var MCP_METHODS = {
204
+ // Lifecycle
205
+ INITIALIZE: "initialize",
206
+ INITIALIZED: "notifications/initialized",
207
+ PING: "ping",
208
+ // Tools
209
+ TOOLS_LIST: "tools/list",
210
+ TOOLS_CALL: "tools/call",
211
+ // Resources (for future use)
212
+ RESOURCES_LIST: "resources/list",
213
+ RESOURCES_READ: "resources/read",
214
+ RESOURCES_SUBSCRIBE: "resources/subscribe",
215
+ RESOURCES_UNSUBSCRIBE: "resources/unsubscribe",
216
+ // Prompts (for future use)
217
+ PROMPTS_LIST: "prompts/list",
218
+ PROMPTS_GET: "prompts/get",
219
+ // Notifications
220
+ TOOLS_LIST_CHANGED: "notifications/tools/list_changed",
221
+ RESOURCES_LIST_CHANGED: "notifications/resources/list_changed",
222
+ RESOURCES_UPDATED: "notifications/resources/updated",
223
+ PROMPTS_LIST_CHANGED: "notifications/prompts/list_changed",
224
+ // Elicitation
225
+ ELICITATION_REQUEST: "elicitation/request",
226
+ ELICITATION_RESPONSE: "elicitation/response",
227
+ // Logging
228
+ LOGGING_SET_LEVEL: "logging/setLevel",
229
+ LOGGING_MESSAGE: "notifications/message",
230
+ // Cancellation
231
+ CANCEL: "notifications/cancelled"
232
+ };
233
+ var DEFAULT_CLIENT_INFO = {
234
+ name: "yourgpt-copilot-sdk",
235
+ version: "2.2.0"
236
+ };
237
+ var DEFAULT_CLIENT_CAPABILITIES = {
238
+ roots: {
239
+ listChanged: true
240
+ },
241
+ sampling: {}
242
+ };
243
+ function createInitializeParams(clientInfo, capabilities) {
244
+ return {
245
+ protocolVersion: MCP_PROTOCOL_VERSION,
246
+ clientInfo: {
247
+ ...DEFAULT_CLIENT_INFO,
248
+ ...clientInfo
249
+ },
250
+ capabilities: capabilities ?? DEFAULT_CLIENT_CAPABILITIES
251
+ };
252
+ }
253
+ function createToolsListParams(cursor) {
254
+ if (cursor) {
255
+ return { cursor };
256
+ }
257
+ return {};
258
+ }
259
+ function createToolCallParams(name, args) {
260
+ return {
261
+ name,
262
+ arguments: args
263
+ };
264
+ }
265
+ function createPingParams() {
266
+ return {};
267
+ }
268
+ function isInitializeResult(value) {
269
+ if (!value || typeof value !== "object") return false;
270
+ const v = value;
271
+ return typeof v.protocolVersion === "string" && v.capabilities !== null && typeof v.capabilities === "object" && v.serverInfo !== null && typeof v.serverInfo === "object";
272
+ }
273
+ function isToolsListResult(value) {
274
+ if (!value || typeof value !== "object") return false;
275
+ const v = value;
276
+ return Array.isArray(v.tools);
277
+ }
278
+ function isToolCallResult(value) {
279
+ if (!value || typeof value !== "object") return false;
280
+ const v = value;
281
+ return Array.isArray(v.content);
282
+ }
283
+
284
+ // src/mcp/transports/types.ts
285
+ var BaseTransport = class {
286
+ constructor() {
287
+ this.connected = false;
288
+ }
289
+ onMessage(handler) {
290
+ this.messageHandler = handler;
291
+ }
292
+ onError(handler) {
293
+ this.errorHandler = handler;
294
+ }
295
+ onClose(handler) {
296
+ this.closeHandler = handler;
297
+ }
298
+ isConnected() {
299
+ return this.connected;
300
+ }
301
+ /**
302
+ * Emit a message to the handler
303
+ */
304
+ emitMessage(message) {
305
+ if (this.messageHandler) {
306
+ this.messageHandler(message);
307
+ }
308
+ }
309
+ /**
310
+ * Emit an error to the handler
311
+ */
312
+ emitError(error) {
313
+ if (this.errorHandler) {
314
+ this.errorHandler(error);
315
+ }
316
+ }
317
+ /**
318
+ * Emit close event
319
+ */
320
+ emitClose() {
321
+ this.connected = false;
322
+ if (this.closeHandler) {
323
+ this.closeHandler();
324
+ }
325
+ }
326
+ };
327
+
328
+ // src/mcp/transports/HttpTransport.ts
329
+ var HttpTransport = class extends BaseTransport {
330
+ constructor(options) {
331
+ super();
332
+ this.url = options.url;
333
+ this.headers = options.headers ?? {};
334
+ this.timeout = options.timeout ?? 3e4;
335
+ this.sessionId = options.sessionId;
336
+ }
337
+ /**
338
+ * Connect the HTTP transport
339
+ *
340
+ * For HTTP transport, "connecting" means verifying the endpoint is reachable.
341
+ * The actual session is established during the initialize handshake.
342
+ */
343
+ async connect() {
344
+ if (this.connected) {
345
+ return;
346
+ }
347
+ this.abortController = new AbortController();
348
+ this.connected = true;
349
+ }
350
+ /**
351
+ * Disconnect the HTTP transport
352
+ */
353
+ async disconnect() {
354
+ if (!this.connected) {
355
+ return;
356
+ }
357
+ if (this.eventSource) {
358
+ this.eventSource.close();
359
+ this.eventSource = void 0;
360
+ }
361
+ if (this.abortController) {
362
+ this.abortController.abort();
363
+ this.abortController = void 0;
364
+ }
365
+ this.sessionId = void 0;
366
+ this.connected = false;
367
+ this.emitClose();
368
+ }
369
+ /**
370
+ * Send a JSON-RPC message and handle the response
371
+ */
372
+ async send(message) {
373
+ if (!this.connected) {
374
+ throw new MCPError(
375
+ "Transport not connected",
376
+ JSON_RPC_ERROR_CODES.INTERNAL_ERROR
377
+ );
378
+ }
379
+ try {
380
+ const response = await this.sendRequest(message);
381
+ const contentType = response.headers.get("content-type") || "";
382
+ const newSessionId = response.headers.get("mcp-session-id");
383
+ if (newSessionId) {
384
+ this.sessionId = newSessionId;
385
+ }
386
+ if (contentType.includes("text/event-stream")) {
387
+ await this.handleSSEResponse(response);
388
+ } else if (contentType.includes("application/json")) {
389
+ const text = await response.text();
390
+ if (text.trim()) {
391
+ const messages = this.parseResponseText(text);
392
+ for (const msg of messages) {
393
+ this.emitMessage(msg);
394
+ }
395
+ }
396
+ } else if (!response.ok) {
397
+ throw new MCPError(
398
+ `HTTP error: ${response.status} ${response.statusText}`,
399
+ JSON_RPC_ERROR_CODES.INTERNAL_ERROR
400
+ );
401
+ }
402
+ } catch (error) {
403
+ if (error instanceof MCPError) {
404
+ throw error;
405
+ }
406
+ if (error instanceof Error) {
407
+ if (error.name === "AbortError") {
408
+ throw new MCPError(
409
+ "Request aborted",
410
+ JSON_RPC_ERROR_CODES.INTERNAL_ERROR
411
+ );
412
+ }
413
+ throw new MCPError(
414
+ `Transport error: ${error.message}`,
415
+ JSON_RPC_ERROR_CODES.INTERNAL_ERROR,
416
+ error
417
+ );
418
+ }
419
+ throw new MCPError(
420
+ "Unknown transport error",
421
+ JSON_RPC_ERROR_CODES.INTERNAL_ERROR
422
+ );
423
+ }
424
+ }
425
+ /**
426
+ * Send an HTTP request
427
+ */
428
+ async sendRequest(message) {
429
+ const headers = {
430
+ "Content-Type": "application/json",
431
+ Accept: "application/json, text/event-stream",
432
+ ...this.headers
433
+ };
434
+ if (this.sessionId) {
435
+ headers["Mcp-Session-Id"] = this.sessionId;
436
+ }
437
+ const controller = new AbortController();
438
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
439
+ try {
440
+ const response = await fetch(this.url, {
441
+ method: "POST",
442
+ headers,
443
+ body: JSON.stringify(message),
444
+ signal: controller.signal
445
+ });
446
+ return response;
447
+ } finally {
448
+ clearTimeout(timeoutId);
449
+ }
450
+ }
451
+ /**
452
+ * Handle an SSE response stream
453
+ */
454
+ async handleSSEResponse(response) {
455
+ const reader = response.body?.getReader();
456
+ if (!reader) {
457
+ throw new MCPError(
458
+ "No response body for SSE stream",
459
+ JSON_RPC_ERROR_CODES.INTERNAL_ERROR
460
+ );
461
+ }
462
+ const decoder = new TextDecoder();
463
+ let buffer = "";
464
+ try {
465
+ while (true) {
466
+ const { done, value } = await reader.read();
467
+ if (done) {
468
+ break;
469
+ }
470
+ buffer += decoder.decode(value, { stream: true });
471
+ const events = buffer.split("\n\n");
472
+ buffer = events.pop() || "";
473
+ for (const event of events) {
474
+ if (!event.trim()) continue;
475
+ const lines = event.split("\n");
476
+ let data = "";
477
+ for (const line of lines) {
478
+ if (line.startsWith("data: ")) {
479
+ data += line.slice(6);
480
+ }
481
+ }
482
+ if (data) {
483
+ try {
484
+ const messages = this.parseResponseText(data);
485
+ for (const msg of messages) {
486
+ this.emitMessage(msg);
487
+ }
488
+ } catch {
489
+ }
490
+ }
491
+ }
492
+ }
493
+ } finally {
494
+ reader.releaseLock();
495
+ }
496
+ }
497
+ /**
498
+ * Parse response text into JSON-RPC messages
499
+ */
500
+ parseResponseText(text) {
501
+ const trimmed = text.trim();
502
+ if (!trimmed) {
503
+ return [];
504
+ }
505
+ try {
506
+ const parsed = JSON.parse(trimmed);
507
+ if (Array.isArray(parsed)) {
508
+ return parsed.filter(
509
+ (msg) => this.isValidJsonRpcMessage(msg)
510
+ );
511
+ }
512
+ if (this.isValidJsonRpcMessage(parsed)) {
513
+ return [parsed];
514
+ }
515
+ return [];
516
+ } catch {
517
+ throw new MCPError(
518
+ "Failed to parse JSON-RPC response",
519
+ JSON_RPC_ERROR_CODES.PARSE_ERROR
520
+ );
521
+ }
522
+ }
523
+ /**
524
+ * Validate a JSON-RPC message
525
+ */
526
+ isValidJsonRpcMessage(msg) {
527
+ if (!msg || typeof msg !== "object") {
528
+ return false;
529
+ }
530
+ const m = msg;
531
+ if (m.jsonrpc !== "2.0") {
532
+ return false;
533
+ }
534
+ if ("method" in m && typeof m.method === "string") {
535
+ return true;
536
+ }
537
+ if ("id" in m && ("result" in m || "error" in m)) {
538
+ return true;
539
+ }
540
+ return false;
541
+ }
542
+ /**
543
+ * Start listening for server-initiated events via SSE
544
+ *
545
+ * This is optional and used when the server supports server-initiated
546
+ * notifications (e.g., tools/list_changed).
547
+ */
548
+ startEventStream() {
549
+ if (this.eventSource || typeof EventSource === "undefined") {
550
+ return;
551
+ }
552
+ const url = new URL(this.url);
553
+ if (this.sessionId) {
554
+ url.searchParams.set("sessionId", this.sessionId);
555
+ }
556
+ this.eventSource = new EventSource(url.toString());
557
+ this.eventSource.onmessage = (event) => {
558
+ try {
559
+ const messages = this.parseResponseText(event.data);
560
+ for (const msg of messages) {
561
+ this.emitMessage(msg);
562
+ }
563
+ } catch {
564
+ }
565
+ };
566
+ this.eventSource.onerror = () => {
567
+ this.emitError(new MCPError("SSE connection error"));
568
+ };
569
+ }
570
+ /**
571
+ * Stop the event stream
572
+ */
573
+ stopEventStream() {
574
+ if (this.eventSource) {
575
+ this.eventSource.close();
576
+ this.eventSource = void 0;
577
+ }
578
+ }
579
+ /**
580
+ * Get the current session ID
581
+ */
582
+ getSessionId() {
583
+ return this.sessionId;
584
+ }
585
+ /**
586
+ * Set the session ID (used after initialization)
587
+ */
588
+ setSessionId(sessionId) {
589
+ this.sessionId = sessionId;
590
+ }
591
+ };
592
+
593
+ // src/mcp/tools/MCPToolAdapter.ts
594
+ var MCPToolAdapter = class {
595
+ constructor(clientName) {
596
+ this.clientName = clientName;
597
+ }
598
+ /**
599
+ * Convert an MCP tool to a ToolDefinition
600
+ */
601
+ toToolDefinition(mcpTool, options) {
602
+ const { prefix = true, asServerTool = true, callTool } = options;
603
+ const toolName = prefix ? `${this.clientName}_${mcpTool.name}` : mcpTool.name;
604
+ const originalName = mcpTool.name;
605
+ return {
606
+ name: toolName,
607
+ description: mcpTool.description ?? `MCP tool: ${mcpTool.name}`,
608
+ location: asServerTool ? "server" : "client",
609
+ inputSchema: this.convertInputSchema(mcpTool.inputSchema),
610
+ handler: async (params, context) => {
611
+ try {
612
+ if (context?.signal?.aborted) {
613
+ return {
614
+ success: false,
615
+ error: "Tool execution cancelled"
616
+ };
617
+ }
618
+ const result = await callTool(originalName, params);
619
+ return this.convertResult(result);
620
+ } catch (error) {
621
+ return {
622
+ success: false,
623
+ error: error instanceof Error ? error.message : "Unknown error calling MCP tool"
624
+ };
625
+ }
626
+ },
627
+ // MCP tools display their name as title
628
+ title: this.formatToolTitle(mcpTool.name),
629
+ executingTitle: `Calling ${this.formatToolTitle(mcpTool.name)}...`,
630
+ completedTitle: `${this.formatToolTitle(mcpTool.name)} completed`
631
+ };
632
+ }
633
+ /**
634
+ * Convert multiple MCP tools to ToolDefinitions
635
+ */
636
+ toToolDefinitions(mcpTools, options) {
637
+ return mcpTools.map((tool) => this.toToolDefinition(tool, options));
638
+ }
639
+ /**
640
+ * Convert MCP input schema to SDK ToolInputSchema
641
+ */
642
+ convertInputSchema(mcpSchema) {
643
+ return {
644
+ type: "object",
645
+ properties: mcpSchema.properties ? this.convertProperties(mcpSchema.properties) : {},
646
+ required: mcpSchema.required,
647
+ additionalProperties: mcpSchema.additionalProperties
648
+ };
649
+ }
650
+ /**
651
+ * Convert MCP schema properties to SDK JSONSchemaProperty format
652
+ */
653
+ convertProperties(properties) {
654
+ const converted = {};
655
+ for (const [key, prop] of Object.entries(properties)) {
656
+ converted[key] = this.convertProperty(prop);
657
+ }
658
+ return converted;
659
+ }
660
+ /**
661
+ * Convert a single MCP property to SDK format
662
+ */
663
+ convertProperty(prop) {
664
+ let type = "string";
665
+ if (prop.type) {
666
+ if (Array.isArray(prop.type)) {
667
+ const nonNull = prop.type.find((t) => t !== "null");
668
+ type = nonNull || "string";
669
+ } else {
670
+ type = prop.type;
671
+ }
672
+ }
673
+ const converted = {
674
+ type,
675
+ description: prop.description
676
+ };
677
+ if (prop.enum) {
678
+ converted.enum = prop.enum;
679
+ }
680
+ if (prop.default !== void 0) {
681
+ converted.default = prop.default;
682
+ }
683
+ if (prop.minLength !== void 0) {
684
+ converted.minLength = prop.minLength;
685
+ }
686
+ if (prop.maxLength !== void 0) {
687
+ converted.maxLength = prop.maxLength;
688
+ }
689
+ if (prop.minimum !== void 0) {
690
+ converted.minimum = prop.minimum;
691
+ }
692
+ if (prop.maximum !== void 0) {
693
+ converted.maximum = prop.maximum;
694
+ }
695
+ if (prop.pattern !== void 0) {
696
+ converted.pattern = prop.pattern;
697
+ }
698
+ if (prop.properties) {
699
+ converted.properties = this.convertProperties(prop.properties);
700
+ }
701
+ if (prop.required) {
702
+ converted.required = prop.required;
703
+ }
704
+ if (prop.items) {
705
+ converted.items = this.convertProperty(prop.items);
706
+ }
707
+ return converted;
708
+ }
709
+ /**
710
+ * Convert MCP tool result to SDK ToolResponse
711
+ */
712
+ convertResult(result) {
713
+ const response = {
714
+ success: !result.isError
715
+ };
716
+ const textParts = [];
717
+ const aiContent = [];
718
+ const uiResources = [];
719
+ for (const content of result.content) {
720
+ switch (content.type) {
721
+ case "text":
722
+ textParts.push(content.text);
723
+ break;
724
+ case "image": {
725
+ const img = content;
726
+ aiContent.push({
727
+ type: "image",
728
+ data: img.data,
729
+ mediaType: img.mimeType
730
+ });
731
+ break;
732
+ }
733
+ case "resource": {
734
+ const res = content.resource;
735
+ if (res.uri?.startsWith("ui://")) {
736
+ uiResources.push({
737
+ uri: res.uri,
738
+ mimeType: res.mimeType || "text/html",
739
+ content: res.text,
740
+ // MCP uses "text" field, normalize to "content"
741
+ blob: res.blob
742
+ });
743
+ } else if (res.text) {
744
+ textParts.push(res.text);
745
+ }
746
+ break;
747
+ }
748
+ case "ui": {
749
+ const uiContent = content;
750
+ uiResources.push({
751
+ uri: uiContent.resource.uri,
752
+ mimeType: uiContent.resource.mimeType,
753
+ content: uiContent.resource.content,
754
+ blob: uiContent.resource.blob,
755
+ metadata: uiContent.resource.metadata
756
+ });
757
+ break;
758
+ }
759
+ }
760
+ }
761
+ if (textParts.length > 0) {
762
+ response.message = textParts.join("\n");
763
+ if (textParts.length === 1) {
764
+ try {
765
+ response.data = JSON.parse(textParts[0]);
766
+ } catch {
767
+ response.data = textParts[0];
768
+ }
769
+ } else {
770
+ response.data = textParts;
771
+ }
772
+ }
773
+ if (aiContent.length > 0) {
774
+ response._aiContent = aiContent;
775
+ }
776
+ if (uiResources.length > 0) {
777
+ response._uiResources = uiResources;
778
+ }
779
+ if (result.isError) {
780
+ response.error = textParts.join("\n") || "Tool execution failed";
781
+ }
782
+ return response;
783
+ }
784
+ /**
785
+ * Format tool name as a readable title
786
+ */
787
+ formatToolTitle(name) {
788
+ return name.replace(/[-_]/g, " ").replace(/\b\w/g, (char) => char.toUpperCase());
789
+ }
790
+ };
791
+ function mcpToolToDefinition(clientName, mcpTool, options) {
792
+ const adapter = new MCPToolAdapter(clientName);
793
+ return adapter.toToolDefinition(mcpTool, options);
794
+ }
795
+ function mcpToolsToDefinitions(clientName, mcpTools, options) {
796
+ const adapter = new MCPToolAdapter(clientName);
797
+ return adapter.toToolDefinitions(mcpTools, options);
798
+ }
799
+
800
+ // src/mcp/client/MCPClient.ts
801
+ var MCPClient = class {
802
+ constructor(config, events) {
803
+ this.config = config;
804
+ this.events = events ?? {};
805
+ this.rpcHandler = new JsonRpcHandler({ timeout: config.timeout ?? 3e4 });
806
+ this.toolAdapter = new MCPToolAdapter(config.name);
807
+ this.state = {
808
+ connectionState: "disconnected",
809
+ tools: []
810
+ };
811
+ }
812
+ /**
813
+ * Get the current client state
814
+ */
815
+ getState() {
816
+ return { ...this.state };
817
+ }
818
+ /**
819
+ * Get the client name
820
+ */
821
+ getName() {
822
+ return this.config.name;
823
+ }
824
+ /**
825
+ * Check if client is connected
826
+ */
827
+ isConnected() {
828
+ return this.state.connectionState === "connected";
829
+ }
830
+ /**
831
+ * Connect to the MCP server
832
+ */
833
+ async connect() {
834
+ if (this.state.connectionState === "connected") {
835
+ return;
836
+ }
837
+ if (this.state.connectionState === "connecting") {
838
+ throw new MCPError("Connection already in progress");
839
+ }
840
+ this.setConnectionState("connecting");
841
+ try {
842
+ this.transport = this.createTransport();
843
+ this.transport.onMessage(this.handleMessage.bind(this));
844
+ this.transport.onError(this.handleError.bind(this));
845
+ this.transport.onClose(this.handleClose.bind(this));
846
+ await this.transport.connect();
847
+ await this.initialize();
848
+ this.setConnectionState("connected");
849
+ await this.refreshTools();
850
+ } catch (error) {
851
+ this.setConnectionState(
852
+ "error",
853
+ error instanceof Error ? error.message : "Connection failed"
854
+ );
855
+ throw error;
856
+ }
857
+ }
858
+ /**
859
+ * Disconnect from the MCP server
860
+ */
861
+ async disconnect() {
862
+ if (this.state.connectionState === "disconnected") {
863
+ return;
864
+ }
865
+ this.rpcHandler.cancelAllPending("Client disconnecting");
866
+ if (this.transport) {
867
+ await this.transport.disconnect();
868
+ this.transport = void 0;
869
+ }
870
+ this.state = {
871
+ connectionState: "disconnected",
872
+ tools: []
873
+ };
874
+ }
875
+ /**
876
+ * Call an MCP tool
877
+ */
878
+ async callTool(name, args) {
879
+ this.ensureConnected();
880
+ const result = await this.request(
881
+ MCP_METHODS.TOOLS_CALL,
882
+ createToolCallParams(name, args)
883
+ );
884
+ if (!isToolCallResult(result)) {
885
+ throw new MCPError(
886
+ "Invalid tool call result from server",
887
+ JSON_RPC_ERROR_CODES.INTERNAL_ERROR
888
+ );
889
+ }
890
+ return result;
891
+ }
892
+ /**
893
+ * Refresh the list of available tools
894
+ */
895
+ async refreshTools() {
896
+ this.ensureConnected();
897
+ const allTools = [];
898
+ let cursor;
899
+ do {
900
+ const result = await this.request(
901
+ MCP_METHODS.TOOLS_LIST,
902
+ createToolsListParams(cursor)
903
+ );
904
+ if (!isToolsListResult(result)) {
905
+ throw new MCPError(
906
+ "Invalid tools list result from server",
907
+ JSON_RPC_ERROR_CODES.INTERNAL_ERROR
908
+ );
909
+ }
910
+ allTools.push(...result.tools);
911
+ cursor = result.nextCursor;
912
+ } while (cursor);
913
+ this.state.tools = allTools;
914
+ this.state.lastActivity = Date.now();
915
+ this.events.onToolsChange?.(allTools);
916
+ return allTools;
917
+ }
918
+ /**
919
+ * Convert MCP tools to ToolDefinition format for use with CopilotProvider
920
+ */
921
+ toToolDefinitions(options) {
922
+ const prefix = options?.prefixToolNames !== false;
923
+ const asServer = options?.serverLocation ?? false;
924
+ return this.state.tools.map(
925
+ (tool) => this.toolAdapter.toToolDefinition(tool, {
926
+ prefix,
927
+ asServerTool: asServer,
928
+ callTool: this.callTool.bind(this)
929
+ })
930
+ );
931
+ }
932
+ /**
933
+ * Get the list of MCP tools
934
+ */
935
+ getTools() {
936
+ return [...this.state.tools];
937
+ }
938
+ /**
939
+ * Get server info
940
+ */
941
+ getServerInfo() {
942
+ return this.state.serverInfo;
943
+ }
944
+ /**
945
+ * Get server capabilities
946
+ */
947
+ getServerCapabilities() {
948
+ return this.state.serverCapabilities;
949
+ }
950
+ /**
951
+ * Ping the server to check connectivity
952
+ */
953
+ async ping() {
954
+ try {
955
+ await this.request(MCP_METHODS.PING, createPingParams());
956
+ return true;
957
+ } catch {
958
+ return false;
959
+ }
960
+ }
961
+ // ============================================
962
+ // Private Methods
963
+ // ============================================
964
+ /**
965
+ * Create transport based on config
966
+ */
967
+ createTransport() {
968
+ switch (this.config.transport) {
969
+ case "http":
970
+ if (!this.config.url) {
971
+ throw new MCPError(
972
+ "URL is required for HTTP transport",
973
+ JSON_RPC_ERROR_CODES.INVALID_PARAMS
974
+ );
975
+ }
976
+ return new HttpTransport({
977
+ url: this.config.url,
978
+ headers: this.config.headers,
979
+ timeout: this.config.timeout
980
+ });
981
+ case "sse":
982
+ if (!this.config.url) {
983
+ throw new MCPError(
984
+ "URL is required for SSE transport",
985
+ JSON_RPC_ERROR_CODES.INVALID_PARAMS
986
+ );
987
+ }
988
+ return new HttpTransport({
989
+ url: this.config.url,
990
+ headers: this.config.headers,
991
+ timeout: this.config.timeout
992
+ });
993
+ case "stdio":
994
+ throw new MCPError(
995
+ "Stdio transport not yet implemented. Use HTTP or SSE transport.",
996
+ JSON_RPC_ERROR_CODES.INTERNAL_ERROR
997
+ );
998
+ default:
999
+ throw new MCPError(
1000
+ `Unknown transport type: ${this.config.transport}`,
1001
+ JSON_RPC_ERROR_CODES.INVALID_PARAMS
1002
+ );
1003
+ }
1004
+ }
1005
+ /**
1006
+ * Perform MCP initialization handshake
1007
+ */
1008
+ async initialize() {
1009
+ const params = createInitializeParams(
1010
+ this.config.clientInfo,
1011
+ this.config.capabilities
1012
+ );
1013
+ const result = await this.request(
1014
+ MCP_METHODS.INITIALIZE,
1015
+ params
1016
+ );
1017
+ if (!isInitializeResult(result)) {
1018
+ throw new MCPError(
1019
+ "Invalid initialization result from server",
1020
+ JSON_RPC_ERROR_CODES.INTERNAL_ERROR
1021
+ );
1022
+ }
1023
+ this.state.serverInfo = result.serverInfo;
1024
+ this.state.serverCapabilities = result.capabilities;
1025
+ await this.notify(MCP_METHODS.INITIALIZED);
1026
+ }
1027
+ /**
1028
+ * Send a JSON-RPC request and wait for response
1029
+ */
1030
+ async request(method, params) {
1031
+ if (!this.transport) {
1032
+ throw new MCPError(
1033
+ "Transport not initialized",
1034
+ JSON_RPC_ERROR_CODES.INTERNAL_ERROR
1035
+ );
1036
+ }
1037
+ const request = this.rpcHandler.createRequest(method, params);
1038
+ const responsePromise = this.rpcHandler.registerRequest(
1039
+ request,
1040
+ this.config.timeout
1041
+ );
1042
+ await this.transport.send(request);
1043
+ return responsePromise;
1044
+ }
1045
+ /**
1046
+ * Send a JSON-RPC notification (no response expected)
1047
+ */
1048
+ async notify(method, params) {
1049
+ if (!this.transport) {
1050
+ throw new MCPError(
1051
+ "Transport not initialized",
1052
+ JSON_RPC_ERROR_CODES.INTERNAL_ERROR
1053
+ );
1054
+ }
1055
+ const notification = this.rpcHandler.createNotification(method, params);
1056
+ await this.transport.send(notification);
1057
+ }
1058
+ /**
1059
+ * Handle incoming JSON-RPC message
1060
+ */
1061
+ handleMessage(message) {
1062
+ if (this.rpcHandler.isResponse(message)) {
1063
+ this.rpcHandler.handleResponse(message);
1064
+ return;
1065
+ }
1066
+ if (this.rpcHandler.isNotification(message)) {
1067
+ const notification = message;
1068
+ this.handleNotification(notification.method, notification.params);
1069
+ return;
1070
+ }
1071
+ if (this.rpcHandler.isRequest(message)) {
1072
+ const request = message;
1073
+ this.handleServerRequest(request.id, request.method, request.params);
1074
+ }
1075
+ }
1076
+ /**
1077
+ * Handle server notification
1078
+ */
1079
+ handleNotification(method, params) {
1080
+ switch (method) {
1081
+ case MCP_METHODS.TOOLS_LIST_CHANGED:
1082
+ this.refreshTools().catch((error) => {
1083
+ this.events.onError?.(error);
1084
+ });
1085
+ break;
1086
+ default:
1087
+ this.events.onNotification?.(method, params);
1088
+ }
1089
+ }
1090
+ /**
1091
+ * Handle server-initiated request (e.g., elicitation)
1092
+ */
1093
+ async handleServerRequest(_id, method, params) {
1094
+ if (method === MCP_METHODS.ELICITATION_REQUEST && this.events.onElicitationRequest) {
1095
+ try {
1096
+ const elicitationRequest = params;
1097
+ const response = await this.events.onElicitationRequest(elicitationRequest);
1098
+ await this.notify(
1099
+ MCP_METHODS.ELICITATION_RESPONSE,
1100
+ response
1101
+ );
1102
+ } catch (error) {
1103
+ await this.notify(MCP_METHODS.ELICITATION_RESPONSE, {
1104
+ requestId: params?.requestId,
1105
+ accepted: false,
1106
+ reason: error instanceof Error ? error.message : "User rejected"
1107
+ });
1108
+ }
1109
+ }
1110
+ }
1111
+ /**
1112
+ * Handle transport error
1113
+ */
1114
+ handleError(error) {
1115
+ this.setConnectionState("error", error.message);
1116
+ this.events.onError?.(error);
1117
+ }
1118
+ /**
1119
+ * Handle transport close
1120
+ */
1121
+ handleClose() {
1122
+ if (this.state.connectionState === "connected") {
1123
+ this.setConnectionState("disconnected");
1124
+ }
1125
+ }
1126
+ /**
1127
+ * Update connection state
1128
+ */
1129
+ setConnectionState(state, error) {
1130
+ this.state.connectionState = state;
1131
+ this.state.error = error;
1132
+ this.events.onConnectionStateChange?.(state);
1133
+ }
1134
+ /**
1135
+ * Ensure client is connected
1136
+ */
1137
+ ensureConnected() {
1138
+ if (!this.isConnected()) {
1139
+ throw new MCPError(
1140
+ "Client not connected. Call connect() first.",
1141
+ JSON_RPC_ERROR_CODES.INTERNAL_ERROR
1142
+ );
1143
+ }
1144
+ }
1145
+ };
1146
+ function createMCPClient(config, events) {
1147
+ return new MCPClient(config, events);
1148
+ }
1149
+
1150
+ export { BaseTransport, DEFAULT_CLIENT_CAPABILITIES, DEFAULT_CLIENT_INFO, HttpTransport, JSON_RPC_ERROR_CODES, JsonRpcHandler, MCPClient, MCPError, MCPToolAdapter, MCP_METHODS, MCP_PROTOCOL_VERSION, createInitializeParams, createMCPClient, createToolCallParams, createToolsListParams, mcpToolToDefinition, mcpToolsToDefinitions };
1151
+ //# sourceMappingURL=chunk-BH7MNDWW.js.map
1152
+ //# sourceMappingURL=chunk-BH7MNDWW.js.map