@contextvm/mcp-sdk 1.27.1-contextvm.0

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 (261) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +141 -0
  3. package/dist/cjs/client/index.d.ts +588 -0
  4. package/dist/cjs/client/index.d.ts.map +1 -0
  5. package/dist/cjs/client/index.js +629 -0
  6. package/dist/cjs/client/index.js.map +1 -0
  7. package/dist/cjs/client/stdio.d.ts +77 -0
  8. package/dist/cjs/client/stdio.d.ts.map +1 -0
  9. package/dist/cjs/client/stdio.js +199 -0
  10. package/dist/cjs/client/stdio.js.map +1 -0
  11. package/dist/cjs/experimental/index.d.ts +13 -0
  12. package/dist/cjs/experimental/index.d.ts.map +1 -0
  13. package/dist/cjs/experimental/index.js +29 -0
  14. package/dist/cjs/experimental/index.js.map +1 -0
  15. package/dist/cjs/experimental/tasks/client.d.ts +121 -0
  16. package/dist/cjs/experimental/tasks/client.d.ts.map +1 -0
  17. package/dist/cjs/experimental/tasks/client.js +188 -0
  18. package/dist/cjs/experimental/tasks/client.js.map +1 -0
  19. package/dist/cjs/experimental/tasks/helpers.d.ts +47 -0
  20. package/dist/cjs/experimental/tasks/helpers.d.ts.map +1 -0
  21. package/dist/cjs/experimental/tasks/helpers.js +68 -0
  22. package/dist/cjs/experimental/tasks/helpers.js.map +1 -0
  23. package/dist/cjs/experimental/tasks/index.d.ts +16 -0
  24. package/dist/cjs/experimental/tasks/index.d.ts.map +1 -0
  25. package/dist/cjs/experimental/tasks/index.js +39 -0
  26. package/dist/cjs/experimental/tasks/index.js.map +1 -0
  27. package/dist/cjs/experimental/tasks/interfaces.d.ts +232 -0
  28. package/dist/cjs/experimental/tasks/interfaces.d.ts.map +1 -0
  29. package/dist/cjs/experimental/tasks/interfaces.js +19 -0
  30. package/dist/cjs/experimental/tasks/interfaces.js.map +1 -0
  31. package/dist/cjs/experimental/tasks/mcp-server.d.ts +77 -0
  32. package/dist/cjs/experimental/tasks/mcp-server.d.ts.map +1 -0
  33. package/dist/cjs/experimental/tasks/mcp-server.js +36 -0
  34. package/dist/cjs/experimental/tasks/mcp-server.js.map +1 -0
  35. package/dist/cjs/experimental/tasks/server.d.ts +170 -0
  36. package/dist/cjs/experimental/tasks/server.d.ts.map +1 -0
  37. package/dist/cjs/experimental/tasks/server.js +250 -0
  38. package/dist/cjs/experimental/tasks/server.js.map +1 -0
  39. package/dist/cjs/experimental/tasks/stores/in-memory.d.ts +94 -0
  40. package/dist/cjs/experimental/tasks/stores/in-memory.d.ts.map +1 -0
  41. package/dist/cjs/experimental/tasks/stores/in-memory.js +251 -0
  42. package/dist/cjs/experimental/tasks/stores/in-memory.js.map +1 -0
  43. package/dist/cjs/experimental/tasks/types.d.ts +10 -0
  44. package/dist/cjs/experimental/tasks/types.d.ts.map +1 -0
  45. package/dist/cjs/experimental/tasks/types.js +28 -0
  46. package/dist/cjs/experimental/tasks/types.js.map +1 -0
  47. package/dist/cjs/inMemory.d.ts +31 -0
  48. package/dist/cjs/inMemory.d.ts.map +1 -0
  49. package/dist/cjs/inMemory.js +51 -0
  50. package/dist/cjs/inMemory.js.map +1 -0
  51. package/dist/cjs/package.json +1 -0
  52. package/dist/cjs/server/completable.d.ts +38 -0
  53. package/dist/cjs/server/completable.d.ts.map +1 -0
  54. package/dist/cjs/server/completable.js +48 -0
  55. package/dist/cjs/server/completable.js.map +1 -0
  56. package/dist/cjs/server/index.d.ts +196 -0
  57. package/dist/cjs/server/index.d.ts.map +1 -0
  58. package/dist/cjs/server/index.js +444 -0
  59. package/dist/cjs/server/index.js.map +1 -0
  60. package/dist/cjs/server/mcp.d.ts +364 -0
  61. package/dist/cjs/server/mcp.d.ts.map +1 -0
  62. package/dist/cjs/server/mcp.js +918 -0
  63. package/dist/cjs/server/mcp.js.map +1 -0
  64. package/dist/cjs/server/stdio.d.ts +28 -0
  65. package/dist/cjs/server/stdio.d.ts.map +1 -0
  66. package/dist/cjs/server/stdio.js +82 -0
  67. package/dist/cjs/server/stdio.js.map +1 -0
  68. package/dist/cjs/server/zod-compat.d.ts +84 -0
  69. package/dist/cjs/server/zod-compat.d.ts.map +1 -0
  70. package/dist/cjs/server/zod-compat.js +244 -0
  71. package/dist/cjs/server/zod-compat.js.map +1 -0
  72. package/dist/cjs/server/zod-json-schema-compat.d.ts +12 -0
  73. package/dist/cjs/server/zod-json-schema-compat.d.ts.map +1 -0
  74. package/dist/cjs/server/zod-json-schema-compat.js +79 -0
  75. package/dist/cjs/server/zod-json-schema-compat.js.map +1 -0
  76. package/dist/cjs/shared/auth-info.d.ts +32 -0
  77. package/dist/cjs/shared/auth-info.d.ts.map +1 -0
  78. package/dist/cjs/shared/auth-info.js +3 -0
  79. package/dist/cjs/shared/auth-info.js.map +1 -0
  80. package/dist/cjs/shared/metadataUtils.d.ts +16 -0
  81. package/dist/cjs/shared/metadataUtils.d.ts.map +1 -0
  82. package/dist/cjs/shared/metadataUtils.js +25 -0
  83. package/dist/cjs/shared/metadataUtils.js.map +1 -0
  84. package/dist/cjs/shared/protocol.d.ts +443 -0
  85. package/dist/cjs/shared/protocol.d.ts.map +1 -0
  86. package/dist/cjs/shared/protocol.js +1104 -0
  87. package/dist/cjs/shared/protocol.js.map +1 -0
  88. package/dist/cjs/shared/responseMessage.d.ts +45 -0
  89. package/dist/cjs/shared/responseMessage.d.ts.map +1 -0
  90. package/dist/cjs/shared/responseMessage.js +23 -0
  91. package/dist/cjs/shared/responseMessage.js.map +1 -0
  92. package/dist/cjs/shared/stdio.d.ts +13 -0
  93. package/dist/cjs/shared/stdio.d.ts.map +1 -0
  94. package/dist/cjs/shared/stdio.js +37 -0
  95. package/dist/cjs/shared/stdio.js.map +1 -0
  96. package/dist/cjs/shared/toolNameValidation.d.ts +31 -0
  97. package/dist/cjs/shared/toolNameValidation.d.ts.map +1 -0
  98. package/dist/cjs/shared/toolNameValidation.js +97 -0
  99. package/dist/cjs/shared/toolNameValidation.js.map +1 -0
  100. package/dist/cjs/shared/transport.d.ts +89 -0
  101. package/dist/cjs/shared/transport.d.ts.map +1 -0
  102. package/dist/cjs/shared/transport.js +43 -0
  103. package/dist/cjs/shared/transport.js.map +1 -0
  104. package/dist/cjs/shared/uriTemplate.d.ts +25 -0
  105. package/dist/cjs/shared/uriTemplate.d.ts.map +1 -0
  106. package/dist/cjs/shared/uriTemplate.js +243 -0
  107. package/dist/cjs/shared/uriTemplate.js.map +1 -0
  108. package/dist/cjs/spec.types.d.ts +2299 -0
  109. package/dist/cjs/spec.types.d.ts.map +1 -0
  110. package/dist/cjs/spec.types.js +27 -0
  111. package/dist/cjs/spec.types.js.map +1 -0
  112. package/dist/cjs/types.d.ts +8137 -0
  113. package/dist/cjs/types.d.ts.map +1 -0
  114. package/dist/cjs/types.js +2092 -0
  115. package/dist/cjs/types.js.map +1 -0
  116. package/dist/cjs/validation/ajv-provider.d.ts +53 -0
  117. package/dist/cjs/validation/ajv-provider.d.ts.map +1 -0
  118. package/dist/cjs/validation/ajv-provider.js +94 -0
  119. package/dist/cjs/validation/ajv-provider.js.map +1 -0
  120. package/dist/cjs/validation/cfworker-provider.d.ts +51 -0
  121. package/dist/cjs/validation/cfworker-provider.d.ts.map +1 -0
  122. package/dist/cjs/validation/cfworker-provider.js +69 -0
  123. package/dist/cjs/validation/cfworker-provider.js.map +1 -0
  124. package/dist/cjs/validation/index.d.ts +29 -0
  125. package/dist/cjs/validation/index.d.ts.map +1 -0
  126. package/dist/cjs/validation/index.js +30 -0
  127. package/dist/cjs/validation/index.js.map +1 -0
  128. package/dist/cjs/validation/types.d.ts +65 -0
  129. package/dist/cjs/validation/types.d.ts.map +1 -0
  130. package/dist/cjs/validation/types.js +3 -0
  131. package/dist/cjs/validation/types.js.map +1 -0
  132. package/dist/esm/client/index.d.ts +588 -0
  133. package/dist/esm/client/index.d.ts.map +1 -0
  134. package/dist/esm/client/index.js +624 -0
  135. package/dist/esm/client/index.js.map +1 -0
  136. package/dist/esm/client/stdio.d.ts +77 -0
  137. package/dist/esm/client/stdio.d.ts.map +1 -0
  138. package/dist/esm/client/stdio.js +191 -0
  139. package/dist/esm/client/stdio.js.map +1 -0
  140. package/dist/esm/experimental/index.d.ts +13 -0
  141. package/dist/esm/experimental/index.d.ts.map +1 -0
  142. package/dist/esm/experimental/index.js +13 -0
  143. package/dist/esm/experimental/index.js.map +1 -0
  144. package/dist/esm/experimental/tasks/client.d.ts +121 -0
  145. package/dist/esm/experimental/tasks/client.d.ts.map +1 -0
  146. package/dist/esm/experimental/tasks/client.js +184 -0
  147. package/dist/esm/experimental/tasks/client.js.map +1 -0
  148. package/dist/esm/experimental/tasks/helpers.d.ts +47 -0
  149. package/dist/esm/experimental/tasks/helpers.d.ts.map +1 -0
  150. package/dist/esm/experimental/tasks/helpers.js +64 -0
  151. package/dist/esm/experimental/tasks/helpers.js.map +1 -0
  152. package/dist/esm/experimental/tasks/index.d.ts +16 -0
  153. package/dist/esm/experimental/tasks/index.d.ts.map +1 -0
  154. package/dist/esm/experimental/tasks/index.js +20 -0
  155. package/dist/esm/experimental/tasks/index.js.map +1 -0
  156. package/dist/esm/experimental/tasks/interfaces.d.ts +232 -0
  157. package/dist/esm/experimental/tasks/interfaces.d.ts.map +1 -0
  158. package/dist/esm/experimental/tasks/interfaces.js +16 -0
  159. package/dist/esm/experimental/tasks/interfaces.js.map +1 -0
  160. package/dist/esm/experimental/tasks/mcp-server.d.ts +77 -0
  161. package/dist/esm/experimental/tasks/mcp-server.d.ts.map +1 -0
  162. package/dist/esm/experimental/tasks/mcp-server.js +32 -0
  163. package/dist/esm/experimental/tasks/mcp-server.js.map +1 -0
  164. package/dist/esm/experimental/tasks/server.d.ts +170 -0
  165. package/dist/esm/experimental/tasks/server.d.ts.map +1 -0
  166. package/dist/esm/experimental/tasks/server.js +246 -0
  167. package/dist/esm/experimental/tasks/server.js.map +1 -0
  168. package/dist/esm/experimental/tasks/stores/in-memory.d.ts +94 -0
  169. package/dist/esm/experimental/tasks/stores/in-memory.d.ts.map +1 -0
  170. package/dist/esm/experimental/tasks/stores/in-memory.js +246 -0
  171. package/dist/esm/experimental/tasks/stores/in-memory.js.map +1 -0
  172. package/dist/esm/experimental/tasks/types.d.ts +10 -0
  173. package/dist/esm/experimental/tasks/types.d.ts.map +1 -0
  174. package/dist/esm/experimental/tasks/types.js +10 -0
  175. package/dist/esm/experimental/tasks/types.js.map +1 -0
  176. package/dist/esm/inMemory.d.ts +31 -0
  177. package/dist/esm/inMemory.d.ts.map +1 -0
  178. package/dist/esm/inMemory.js +47 -0
  179. package/dist/esm/inMemory.js.map +1 -0
  180. package/dist/esm/package.json +1 -0
  181. package/dist/esm/server/completable.d.ts +38 -0
  182. package/dist/esm/server/completable.d.ts.map +1 -0
  183. package/dist/esm/server/completable.js +41 -0
  184. package/dist/esm/server/completable.js.map +1 -0
  185. package/dist/esm/server/index.d.ts +196 -0
  186. package/dist/esm/server/index.d.ts.map +1 -0
  187. package/dist/esm/server/index.js +440 -0
  188. package/dist/esm/server/index.js.map +1 -0
  189. package/dist/esm/server/mcp.d.ts +364 -0
  190. package/dist/esm/server/mcp.d.ts.map +1 -0
  191. package/dist/esm/server/mcp.js +913 -0
  192. package/dist/esm/server/mcp.js.map +1 -0
  193. package/dist/esm/server/stdio.d.ts +28 -0
  194. package/dist/esm/server/stdio.d.ts.map +1 -0
  195. package/dist/esm/server/stdio.js +75 -0
  196. package/dist/esm/server/stdio.js.map +1 -0
  197. package/dist/esm/server/zod-compat.d.ts +84 -0
  198. package/dist/esm/server/zod-compat.d.ts.map +1 -0
  199. package/dist/esm/server/zod-compat.js +209 -0
  200. package/dist/esm/server/zod-compat.js.map +1 -0
  201. package/dist/esm/server/zod-json-schema-compat.d.ts +12 -0
  202. package/dist/esm/server/zod-json-schema-compat.d.ts.map +1 -0
  203. package/dist/esm/server/zod-json-schema-compat.js +51 -0
  204. package/dist/esm/server/zod-json-schema-compat.js.map +1 -0
  205. package/dist/esm/shared/auth-info.d.ts +32 -0
  206. package/dist/esm/shared/auth-info.d.ts.map +1 -0
  207. package/dist/esm/shared/auth-info.js +2 -0
  208. package/dist/esm/shared/auth-info.js.map +1 -0
  209. package/dist/esm/shared/metadataUtils.d.ts +16 -0
  210. package/dist/esm/shared/metadataUtils.d.ts.map +1 -0
  211. package/dist/esm/shared/metadataUtils.js +22 -0
  212. package/dist/esm/shared/metadataUtils.js.map +1 -0
  213. package/dist/esm/shared/protocol.d.ts +443 -0
  214. package/dist/esm/shared/protocol.d.ts.map +1 -0
  215. package/dist/esm/shared/protocol.js +1099 -0
  216. package/dist/esm/shared/protocol.js.map +1 -0
  217. package/dist/esm/shared/responseMessage.d.ts +45 -0
  218. package/dist/esm/shared/responseMessage.d.ts.map +1 -0
  219. package/dist/esm/shared/responseMessage.js +19 -0
  220. package/dist/esm/shared/responseMessage.js.map +1 -0
  221. package/dist/esm/shared/stdio.d.ts +13 -0
  222. package/dist/esm/shared/stdio.d.ts.map +1 -0
  223. package/dist/esm/shared/stdio.js +31 -0
  224. package/dist/esm/shared/stdio.js.map +1 -0
  225. package/dist/esm/shared/toolNameValidation.d.ts +31 -0
  226. package/dist/esm/shared/toolNameValidation.d.ts.map +1 -0
  227. package/dist/esm/shared/toolNameValidation.js +92 -0
  228. package/dist/esm/shared/toolNameValidation.js.map +1 -0
  229. package/dist/esm/shared/transport.d.ts +89 -0
  230. package/dist/esm/shared/transport.d.ts.map +1 -0
  231. package/dist/esm/shared/transport.js +39 -0
  232. package/dist/esm/shared/transport.js.map +1 -0
  233. package/dist/esm/shared/uriTemplate.d.ts +25 -0
  234. package/dist/esm/shared/uriTemplate.d.ts.map +1 -0
  235. package/dist/esm/shared/uriTemplate.js +239 -0
  236. package/dist/esm/shared/uriTemplate.js.map +1 -0
  237. package/dist/esm/spec.types.d.ts +2299 -0
  238. package/dist/esm/spec.types.d.ts.map +1 -0
  239. package/dist/esm/spec.types.js +24 -0
  240. package/dist/esm/spec.types.js.map +1 -0
  241. package/dist/esm/types.d.ts +8137 -0
  242. package/dist/esm/types.d.ts.map +1 -0
  243. package/dist/esm/types.js +2052 -0
  244. package/dist/esm/types.js.map +1 -0
  245. package/dist/esm/validation/ajv-provider.d.ts +53 -0
  246. package/dist/esm/validation/ajv-provider.d.ts.map +1 -0
  247. package/dist/esm/validation/ajv-provider.js +87 -0
  248. package/dist/esm/validation/ajv-provider.js.map +1 -0
  249. package/dist/esm/validation/cfworker-provider.d.ts +51 -0
  250. package/dist/esm/validation/cfworker-provider.d.ts.map +1 -0
  251. package/dist/esm/validation/cfworker-provider.js +65 -0
  252. package/dist/esm/validation/cfworker-provider.js.map +1 -0
  253. package/dist/esm/validation/index.d.ts +29 -0
  254. package/dist/esm/validation/index.d.ts.map +1 -0
  255. package/dist/esm/validation/index.js +29 -0
  256. package/dist/esm/validation/index.js.map +1 -0
  257. package/dist/esm/validation/types.d.ts +65 -0
  258. package/dist/esm/validation/types.d.ts.map +1 -0
  259. package/dist/esm/validation/types.js +2 -0
  260. package/dist/esm/validation/types.js.map +1 -0
  261. package/package.json +124 -0
@@ -0,0 +1,196 @@
1
+ import { Protocol, type NotificationOptions, type ProtocolOptions, type RequestOptions } from '../shared/protocol.js';
2
+ import { type ClientCapabilities, type CreateMessageRequest, type CreateMessageResult, type CreateMessageResultWithTools, type CreateMessageRequestParamsBase, type CreateMessageRequestParamsWithTools, type ElicitRequestFormParams, type ElicitRequestURLParams, type ElicitResult, type Implementation, type ListRootsRequest, type LoggingMessageNotification, type ResourceUpdatedNotification, type ServerCapabilities, type ServerNotification, type ServerRequest, type ServerResult, type Request, type Notification, type Result } from '../types.js';
3
+ import type { jsonSchemaValidator } from '../validation/types.js';
4
+ import { AnyObjectSchema, SchemaOutput } from './zod-compat.js';
5
+ import { RequestHandlerExtra } from '../shared/protocol.js';
6
+ import { ExperimentalServerTasks } from '../experimental/tasks/server.js';
7
+ export type ServerOptions = ProtocolOptions & {
8
+ /**
9
+ * Capabilities to advertise as being supported by this server.
10
+ */
11
+ capabilities?: ServerCapabilities;
12
+ /**
13
+ * Optional instructions describing how to use the server and its features.
14
+ */
15
+ instructions?: string;
16
+ /**
17
+ * JSON Schema validator for elicitation response validation.
18
+ *
19
+ * The validator is used to validate user input returned from elicitation
20
+ * requests against the requested schema.
21
+ *
22
+ * @default AjvJsonSchemaValidator
23
+ *
24
+ * @example
25
+ * ```typescript
26
+ * // ajv (default)
27
+ * const server = new Server(
28
+ * { name: 'my-server', version: '1.0.0' },
29
+ * {
30
+ * capabilities: {}
31
+ * jsonSchemaValidator: new AjvJsonSchemaValidator()
32
+ * }
33
+ * );
34
+ *
35
+ * // @cfworker/json-schema
36
+ * const server = new Server(
37
+ * { name: 'my-server', version: '1.0.0' },
38
+ * {
39
+ * capabilities: {},
40
+ * jsonSchemaValidator: new CfWorkerJsonSchemaValidator()
41
+ * }
42
+ * );
43
+ * ```
44
+ */
45
+ jsonSchemaValidator?: jsonSchemaValidator;
46
+ };
47
+ /**
48
+ * An MCP server on top of a pluggable transport.
49
+ *
50
+ * This server will automatically respond to the initialization flow as initiated from the client.
51
+ *
52
+ * To use with custom types, extend the base Request/Notification/Result types and pass them as type parameters:
53
+ *
54
+ * ```typescript
55
+ * // Custom schemas
56
+ * const CustomRequestSchema = RequestSchema.extend({...})
57
+ * const CustomNotificationSchema = NotificationSchema.extend({...})
58
+ * const CustomResultSchema = ResultSchema.extend({...})
59
+ *
60
+ * // Type aliases
61
+ * type CustomRequest = z.infer<typeof CustomRequestSchema>
62
+ * type CustomNotification = z.infer<typeof CustomNotificationSchema>
63
+ * type CustomResult = z.infer<typeof CustomResultSchema>
64
+ *
65
+ * // Create typed server
66
+ * const server = new Server<CustomRequest, CustomNotification, CustomResult>({
67
+ * name: "CustomServer",
68
+ * version: "1.0.0"
69
+ * })
70
+ * ```
71
+ * @deprecated Use `McpServer` instead for the high-level API. Only use `Server` for advanced use cases.
72
+ */
73
+ export declare class Server<RequestT extends Request = Request, NotificationT extends Notification = Notification, ResultT extends Result = Result> extends Protocol<ServerRequest | RequestT, ServerNotification | NotificationT, ServerResult | ResultT> {
74
+ private _serverInfo;
75
+ private _clientCapabilities?;
76
+ private _clientVersion?;
77
+ private _capabilities;
78
+ private _instructions?;
79
+ private _jsonSchemaValidator;
80
+ private _experimental?;
81
+ /**
82
+ * Callback for when initialization has fully completed (i.e., the client has sent an `initialized` notification).
83
+ */
84
+ oninitialized?: () => void;
85
+ /**
86
+ * Initializes this server with the given name and version information.
87
+ */
88
+ constructor(_serverInfo: Implementation, options?: ServerOptions);
89
+ /**
90
+ * Access experimental features.
91
+ *
92
+ * WARNING: These APIs are experimental and may change without notice.
93
+ *
94
+ * @experimental
95
+ */
96
+ get experimental(): {
97
+ tasks: ExperimentalServerTasks<RequestT, NotificationT, ResultT>;
98
+ };
99
+ private _loggingLevels;
100
+ private readonly LOG_LEVEL_SEVERITY;
101
+ private isMessageIgnored;
102
+ /**
103
+ * Registers new capabilities. This can only be called before connecting to a transport.
104
+ *
105
+ * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization).
106
+ */
107
+ registerCapabilities(capabilities: ServerCapabilities): void;
108
+ /**
109
+ * Override request handler registration to enforce server-side validation for tools/call.
110
+ */
111
+ setRequestHandler<T extends AnyObjectSchema>(requestSchema: T, handler: (request: SchemaOutput<T>, extra: RequestHandlerExtra<ServerRequest | RequestT, ServerNotification | NotificationT>) => ServerResult | ResultT | Promise<ServerResult | ResultT>): void;
112
+ protected assertCapabilityForMethod(method: RequestT['method']): void;
113
+ protected assertNotificationCapability(method: (ServerNotification | NotificationT)['method']): void;
114
+ protected assertRequestHandlerCapability(method: string): void;
115
+ protected assertTaskCapability(method: string): void;
116
+ protected assertTaskHandlerCapability(method: string): void;
117
+ private _oninitialize;
118
+ /**
119
+ * After initialization has completed, this will be populated with the client's reported capabilities.
120
+ */
121
+ getClientCapabilities(): ClientCapabilities | undefined;
122
+ /**
123
+ * After initialization has completed, this will be populated with information about the client's name and version.
124
+ */
125
+ getClientVersion(): Implementation | undefined;
126
+ private getCapabilities;
127
+ ping(): Promise<{
128
+ _meta?: {
129
+ [x: string]: unknown;
130
+ progressToken?: string | number | undefined;
131
+ "io.modelcontextprotocol/related-task"?: {
132
+ taskId: string;
133
+ } | undefined;
134
+ } | undefined;
135
+ }>;
136
+ /**
137
+ * Request LLM sampling from the client (without tools).
138
+ * Returns single content block for backwards compatibility.
139
+ */
140
+ createMessage(params: CreateMessageRequestParamsBase, options?: RequestOptions): Promise<CreateMessageResult>;
141
+ /**
142
+ * Request LLM sampling from the client with tool support.
143
+ * Returns content that may be a single block or array (for parallel tool calls).
144
+ */
145
+ createMessage(params: CreateMessageRequestParamsWithTools, options?: RequestOptions): Promise<CreateMessageResultWithTools>;
146
+ /**
147
+ * Request LLM sampling from the client.
148
+ * When tools may or may not be present, returns the union type.
149
+ */
150
+ createMessage(params: CreateMessageRequest['params'], options?: RequestOptions): Promise<CreateMessageResult | CreateMessageResultWithTools>;
151
+ /**
152
+ * Creates an elicitation request for the given parameters.
153
+ * For backwards compatibility, `mode` may be omitted for form requests and will default to `'form'`.
154
+ * @param params The parameters for the elicitation request.
155
+ * @param options Optional request options.
156
+ * @returns The result of the elicitation request.
157
+ */
158
+ elicitInput(params: ElicitRequestFormParams | ElicitRequestURLParams, options?: RequestOptions): Promise<ElicitResult>;
159
+ /**
160
+ * Creates a reusable callback that, when invoked, will send a `notifications/elicitation/complete`
161
+ * notification for the specified elicitation ID.
162
+ *
163
+ * @param elicitationId The ID of the elicitation to mark as complete.
164
+ * @param options Optional notification options. Useful when the completion notification should be related to a prior request.
165
+ * @returns A function that emits the completion notification when awaited.
166
+ */
167
+ createElicitationCompletionNotifier(elicitationId: string, options?: NotificationOptions): () => Promise<void>;
168
+ listRoots(params?: ListRootsRequest['params'], options?: RequestOptions): Promise<{
169
+ [x: string]: unknown;
170
+ roots: {
171
+ uri: string;
172
+ name?: string | undefined;
173
+ _meta?: Record<string, unknown> | undefined;
174
+ }[];
175
+ _meta?: {
176
+ [x: string]: unknown;
177
+ progressToken?: string | number | undefined;
178
+ "io.modelcontextprotocol/related-task"?: {
179
+ taskId: string;
180
+ } | undefined;
181
+ } | undefined;
182
+ }>;
183
+ /**
184
+ * Sends a logging message to the client, if connected.
185
+ * Note: You only need to send the parameters object, not the entire JSON RPC message
186
+ * @see LoggingMessageNotification
187
+ * @param params
188
+ * @param sessionId optional for stateless and backward compatibility
189
+ */
190
+ sendLoggingMessage(params: LoggingMessageNotification['params'], sessionId?: string): Promise<void>;
191
+ sendResourceUpdated(params: ResourceUpdatedNotification['params']): Promise<void>;
192
+ sendResourceListChanged(): Promise<void>;
193
+ sendToolListChanged(): Promise<void>;
194
+ sendPromptListChanged(): Promise<void>;
195
+ }
196
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/server/index.ts"],"names":[],"mappings":"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"}
@@ -0,0 +1,444 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Server = void 0;
4
+ const protocol_js_1 = require("../shared/protocol.js");
5
+ const types_js_1 = require("../types.js");
6
+ const ajv_provider_js_1 = require("../validation/ajv-provider.js");
7
+ const zod_compat_js_1 = require("./zod-compat.js");
8
+ const server_js_1 = require("../experimental/tasks/server.js");
9
+ const helpers_js_1 = require("../experimental/tasks/helpers.js");
10
+ /**
11
+ * An MCP server on top of a pluggable transport.
12
+ *
13
+ * This server will automatically respond to the initialization flow as initiated from the client.
14
+ *
15
+ * To use with custom types, extend the base Request/Notification/Result types and pass them as type parameters:
16
+ *
17
+ * ```typescript
18
+ * // Custom schemas
19
+ * const CustomRequestSchema = RequestSchema.extend({...})
20
+ * const CustomNotificationSchema = NotificationSchema.extend({...})
21
+ * const CustomResultSchema = ResultSchema.extend({...})
22
+ *
23
+ * // Type aliases
24
+ * type CustomRequest = z.infer<typeof CustomRequestSchema>
25
+ * type CustomNotification = z.infer<typeof CustomNotificationSchema>
26
+ * type CustomResult = z.infer<typeof CustomResultSchema>
27
+ *
28
+ * // Create typed server
29
+ * const server = new Server<CustomRequest, CustomNotification, CustomResult>({
30
+ * name: "CustomServer",
31
+ * version: "1.0.0"
32
+ * })
33
+ * ```
34
+ * @deprecated Use `McpServer` instead for the high-level API. Only use `Server` for advanced use cases.
35
+ */
36
+ class Server extends protocol_js_1.Protocol {
37
+ /**
38
+ * Initializes this server with the given name and version information.
39
+ */
40
+ constructor(_serverInfo, options) {
41
+ super(options);
42
+ this._serverInfo = _serverInfo;
43
+ // Map log levels by session id
44
+ this._loggingLevels = new Map();
45
+ // Map LogLevelSchema to severity index
46
+ this.LOG_LEVEL_SEVERITY = new Map(types_js_1.LoggingLevelSchema.options.map((level, index) => [level, index]));
47
+ // Is a message with the given level ignored in the log level set for the given session id?
48
+ this.isMessageIgnored = (level, sessionId) => {
49
+ const currentLevel = this._loggingLevels.get(sessionId);
50
+ return currentLevel ? this.LOG_LEVEL_SEVERITY.get(level) < this.LOG_LEVEL_SEVERITY.get(currentLevel) : false;
51
+ };
52
+ this._capabilities = options?.capabilities ?? {};
53
+ this._instructions = options?.instructions;
54
+ this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new ajv_provider_js_1.AjvJsonSchemaValidator();
55
+ this.setRequestHandler(types_js_1.InitializeRequestSchema, request => this._oninitialize(request));
56
+ this.setNotificationHandler(types_js_1.InitializedNotificationSchema, () => this.oninitialized?.());
57
+ if (this._capabilities.logging) {
58
+ this.setRequestHandler(types_js_1.SetLevelRequestSchema, async (request, extra) => {
59
+ const transportSessionId = extra.sessionId || extra.requestInfo?.headers['mcp-session-id'] || undefined;
60
+ const { level } = request.params;
61
+ const parseResult = types_js_1.LoggingLevelSchema.safeParse(level);
62
+ if (parseResult.success) {
63
+ this._loggingLevels.set(transportSessionId, parseResult.data);
64
+ }
65
+ return {};
66
+ });
67
+ }
68
+ }
69
+ /**
70
+ * Access experimental features.
71
+ *
72
+ * WARNING: These APIs are experimental and may change without notice.
73
+ *
74
+ * @experimental
75
+ */
76
+ get experimental() {
77
+ if (!this._experimental) {
78
+ this._experimental = {
79
+ tasks: new server_js_1.ExperimentalServerTasks(this)
80
+ };
81
+ }
82
+ return this._experimental;
83
+ }
84
+ /**
85
+ * Registers new capabilities. This can only be called before connecting to a transport.
86
+ *
87
+ * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization).
88
+ */
89
+ registerCapabilities(capabilities) {
90
+ if (this.transport) {
91
+ throw new Error('Cannot register capabilities after connecting to transport');
92
+ }
93
+ this._capabilities = (0, protocol_js_1.mergeCapabilities)(this._capabilities, capabilities);
94
+ }
95
+ /**
96
+ * Override request handler registration to enforce server-side validation for tools/call.
97
+ */
98
+ setRequestHandler(requestSchema, handler) {
99
+ const shape = (0, zod_compat_js_1.getObjectShape)(requestSchema);
100
+ const methodSchema = shape?.method;
101
+ if (!methodSchema) {
102
+ throw new Error('Schema is missing a method literal');
103
+ }
104
+ // Extract literal value using type-safe property access
105
+ let methodValue;
106
+ if ((0, zod_compat_js_1.isZ4Schema)(methodSchema)) {
107
+ const v4Schema = methodSchema;
108
+ const v4Def = v4Schema._zod?.def;
109
+ methodValue = v4Def?.value ?? v4Schema.value;
110
+ }
111
+ else {
112
+ const v3Schema = methodSchema;
113
+ const legacyDef = v3Schema._def;
114
+ methodValue = legacyDef?.value ?? v3Schema.value;
115
+ }
116
+ if (typeof methodValue !== 'string') {
117
+ throw new Error('Schema method literal must be a string');
118
+ }
119
+ const method = methodValue;
120
+ if (method === 'tools/call') {
121
+ const wrappedHandler = async (request, extra) => {
122
+ const validatedRequest = (0, zod_compat_js_1.safeParse)(types_js_1.CallToolRequestSchema, request);
123
+ if (!validatedRequest.success) {
124
+ const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);
125
+ throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Invalid tools/call request: ${errorMessage}`);
126
+ }
127
+ const { params } = validatedRequest.data;
128
+ const result = await Promise.resolve(handler(request, extra));
129
+ // When task creation is requested, validate and return CreateTaskResult
130
+ if (params.task) {
131
+ const taskValidationResult = (0, zod_compat_js_1.safeParse)(types_js_1.CreateTaskResultSchema, result);
132
+ if (!taskValidationResult.success) {
133
+ const errorMessage = taskValidationResult.error instanceof Error
134
+ ? taskValidationResult.error.message
135
+ : String(taskValidationResult.error);
136
+ throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`);
137
+ }
138
+ return taskValidationResult.data;
139
+ }
140
+ // For non-task requests, validate against CallToolResultSchema
141
+ const validationResult = (0, zod_compat_js_1.safeParse)(types_js_1.CallToolResultSchema, result);
142
+ if (!validationResult.success) {
143
+ const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);
144
+ throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Invalid tools/call result: ${errorMessage}`);
145
+ }
146
+ return validationResult.data;
147
+ };
148
+ // Install the wrapped handler
149
+ return super.setRequestHandler(requestSchema, wrappedHandler);
150
+ }
151
+ // Other handlers use default behavior
152
+ return super.setRequestHandler(requestSchema, handler);
153
+ }
154
+ assertCapabilityForMethod(method) {
155
+ switch (method) {
156
+ case 'sampling/createMessage':
157
+ if (!this._clientCapabilities?.sampling) {
158
+ throw new Error(`Client does not support sampling (required for ${method})`);
159
+ }
160
+ break;
161
+ case 'elicitation/create':
162
+ if (!this._clientCapabilities?.elicitation) {
163
+ throw new Error(`Client does not support elicitation (required for ${method})`);
164
+ }
165
+ break;
166
+ case 'roots/list':
167
+ if (!this._clientCapabilities?.roots) {
168
+ throw new Error(`Client does not support listing roots (required for ${method})`);
169
+ }
170
+ break;
171
+ case 'ping':
172
+ // No specific capability required for ping
173
+ break;
174
+ }
175
+ }
176
+ assertNotificationCapability(method) {
177
+ switch (method) {
178
+ case 'notifications/message':
179
+ if (!this._capabilities.logging) {
180
+ throw new Error(`Server does not support logging (required for ${method})`);
181
+ }
182
+ break;
183
+ case 'notifications/resources/updated':
184
+ case 'notifications/resources/list_changed':
185
+ if (!this._capabilities.resources) {
186
+ throw new Error(`Server does not support notifying about resources (required for ${method})`);
187
+ }
188
+ break;
189
+ case 'notifications/tools/list_changed':
190
+ if (!this._capabilities.tools) {
191
+ throw new Error(`Server does not support notifying of tool list changes (required for ${method})`);
192
+ }
193
+ break;
194
+ case 'notifications/prompts/list_changed':
195
+ if (!this._capabilities.prompts) {
196
+ throw new Error(`Server does not support notifying of prompt list changes (required for ${method})`);
197
+ }
198
+ break;
199
+ case 'notifications/elicitation/complete':
200
+ if (!this._clientCapabilities?.elicitation?.url) {
201
+ throw new Error(`Client does not support URL elicitation (required for ${method})`);
202
+ }
203
+ break;
204
+ case 'notifications/cancelled':
205
+ // Cancellation notifications are always allowed
206
+ break;
207
+ case 'notifications/progress':
208
+ // Progress notifications are always allowed
209
+ break;
210
+ }
211
+ }
212
+ assertRequestHandlerCapability(method) {
213
+ // Task handlers are registered in Protocol constructor before _capabilities is initialized
214
+ // Skip capability check for task methods during initialization
215
+ if (!this._capabilities) {
216
+ return;
217
+ }
218
+ switch (method) {
219
+ case 'completion/complete':
220
+ if (!this._capabilities.completions) {
221
+ throw new Error(`Server does not support completions (required for ${method})`);
222
+ }
223
+ break;
224
+ case 'logging/setLevel':
225
+ if (!this._capabilities.logging) {
226
+ throw new Error(`Server does not support logging (required for ${method})`);
227
+ }
228
+ break;
229
+ case 'prompts/get':
230
+ case 'prompts/list':
231
+ if (!this._capabilities.prompts) {
232
+ throw new Error(`Server does not support prompts (required for ${method})`);
233
+ }
234
+ break;
235
+ case 'resources/list':
236
+ case 'resources/templates/list':
237
+ case 'resources/read':
238
+ if (!this._capabilities.resources) {
239
+ throw new Error(`Server does not support resources (required for ${method})`);
240
+ }
241
+ break;
242
+ case 'tools/call':
243
+ case 'tools/list':
244
+ if (!this._capabilities.tools) {
245
+ throw new Error(`Server does not support tools (required for ${method})`);
246
+ }
247
+ break;
248
+ case 'tasks/get':
249
+ case 'tasks/list':
250
+ case 'tasks/result':
251
+ case 'tasks/cancel':
252
+ if (!this._capabilities.tasks) {
253
+ throw new Error(`Server does not support tasks capability (required for ${method})`);
254
+ }
255
+ break;
256
+ case 'ping':
257
+ case 'initialize':
258
+ // No specific capability required for these methods
259
+ break;
260
+ }
261
+ }
262
+ assertTaskCapability(method) {
263
+ (0, helpers_js_1.assertClientRequestTaskCapability)(this._clientCapabilities?.tasks?.requests, method, 'Client');
264
+ }
265
+ assertTaskHandlerCapability(method) {
266
+ // Task handlers are registered in Protocol constructor before _capabilities is initialized
267
+ // Skip capability check for task methods during initialization
268
+ if (!this._capabilities) {
269
+ return;
270
+ }
271
+ (0, helpers_js_1.assertToolsCallTaskCapability)(this._capabilities.tasks?.requests, method, 'Server');
272
+ }
273
+ async _oninitialize(request) {
274
+ const requestedVersion = request.params.protocolVersion;
275
+ this._clientCapabilities = request.params.capabilities;
276
+ this._clientVersion = request.params.clientInfo;
277
+ const protocolVersion = types_js_1.SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion) ? requestedVersion : types_js_1.LATEST_PROTOCOL_VERSION;
278
+ return {
279
+ protocolVersion,
280
+ capabilities: this.getCapabilities(),
281
+ serverInfo: this._serverInfo,
282
+ ...(this._instructions && { instructions: this._instructions })
283
+ };
284
+ }
285
+ /**
286
+ * After initialization has completed, this will be populated with the client's reported capabilities.
287
+ */
288
+ getClientCapabilities() {
289
+ return this._clientCapabilities;
290
+ }
291
+ /**
292
+ * After initialization has completed, this will be populated with information about the client's name and version.
293
+ */
294
+ getClientVersion() {
295
+ return this._clientVersion;
296
+ }
297
+ getCapabilities() {
298
+ return this._capabilities;
299
+ }
300
+ async ping() {
301
+ return this.request({ method: 'ping' }, types_js_1.EmptyResultSchema);
302
+ }
303
+ // Implementation
304
+ async createMessage(params, options) {
305
+ // Capability check - only required when tools/toolChoice are provided
306
+ if (params.tools || params.toolChoice) {
307
+ if (!this._clientCapabilities?.sampling?.tools) {
308
+ throw new Error('Client does not support sampling tools capability.');
309
+ }
310
+ }
311
+ // Message structure validation - always validate tool_use/tool_result pairs.
312
+ // These may appear even without tools/toolChoice in the current request when
313
+ // a previous sampling request returned tool_use and this is a follow-up with results.
314
+ if (params.messages.length > 0) {
315
+ const lastMessage = params.messages[params.messages.length - 1];
316
+ const lastContent = Array.isArray(lastMessage.content) ? lastMessage.content : [lastMessage.content];
317
+ const hasToolResults = lastContent.some(c => c.type === 'tool_result');
318
+ const previousMessage = params.messages.length > 1 ? params.messages[params.messages.length - 2] : undefined;
319
+ const previousContent = previousMessage
320
+ ? Array.isArray(previousMessage.content)
321
+ ? previousMessage.content
322
+ : [previousMessage.content]
323
+ : [];
324
+ const hasPreviousToolUse = previousContent.some(c => c.type === 'tool_use');
325
+ if (hasToolResults) {
326
+ if (lastContent.some(c => c.type !== 'tool_result')) {
327
+ throw new Error('The last message must contain only tool_result content if any is present');
328
+ }
329
+ if (!hasPreviousToolUse) {
330
+ throw new Error('tool_result blocks are not matching any tool_use from the previous message');
331
+ }
332
+ }
333
+ if (hasPreviousToolUse) {
334
+ const toolUseIds = new Set(previousContent.filter(c => c.type === 'tool_use').map(c => c.id));
335
+ const toolResultIds = new Set(lastContent.filter(c => c.type === 'tool_result').map(c => c.toolUseId));
336
+ if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every(id => toolResultIds.has(id))) {
337
+ throw new Error('ids of tool_result blocks and tool_use blocks from previous message do not match');
338
+ }
339
+ }
340
+ }
341
+ // Use different schemas based on whether tools are provided
342
+ if (params.tools) {
343
+ return this.request({ method: 'sampling/createMessage', params }, types_js_1.CreateMessageResultWithToolsSchema, options);
344
+ }
345
+ return this.request({ method: 'sampling/createMessage', params }, types_js_1.CreateMessageResultSchema, options);
346
+ }
347
+ /**
348
+ * Creates an elicitation request for the given parameters.
349
+ * For backwards compatibility, `mode` may be omitted for form requests and will default to `'form'`.
350
+ * @param params The parameters for the elicitation request.
351
+ * @param options Optional request options.
352
+ * @returns The result of the elicitation request.
353
+ */
354
+ async elicitInput(params, options) {
355
+ const mode = (params.mode ?? 'form');
356
+ switch (mode) {
357
+ case 'url': {
358
+ if (!this._clientCapabilities?.elicitation?.url) {
359
+ throw new Error('Client does not support url elicitation.');
360
+ }
361
+ const urlParams = params;
362
+ return this.request({ method: 'elicitation/create', params: urlParams }, types_js_1.ElicitResultSchema, options);
363
+ }
364
+ case 'form': {
365
+ if (!this._clientCapabilities?.elicitation?.form) {
366
+ throw new Error('Client does not support form elicitation.');
367
+ }
368
+ const formParams = params.mode === 'form' ? params : { ...params, mode: 'form' };
369
+ const result = await this.request({ method: 'elicitation/create', params: formParams }, types_js_1.ElicitResultSchema, options);
370
+ if (result.action === 'accept' && result.content && formParams.requestedSchema) {
371
+ try {
372
+ const validator = this._jsonSchemaValidator.getValidator(formParams.requestedSchema);
373
+ const validationResult = validator(result.content);
374
+ if (!validationResult.valid) {
375
+ throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Elicitation response content does not match requested schema: ${validationResult.errorMessage}`);
376
+ }
377
+ }
378
+ catch (error) {
379
+ if (error instanceof types_js_1.McpError) {
380
+ throw error;
381
+ }
382
+ throw new types_js_1.McpError(types_js_1.ErrorCode.InternalError, `Error validating elicitation response: ${error instanceof Error ? error.message : String(error)}`);
383
+ }
384
+ }
385
+ return result;
386
+ }
387
+ }
388
+ }
389
+ /**
390
+ * Creates a reusable callback that, when invoked, will send a `notifications/elicitation/complete`
391
+ * notification for the specified elicitation ID.
392
+ *
393
+ * @param elicitationId The ID of the elicitation to mark as complete.
394
+ * @param options Optional notification options. Useful when the completion notification should be related to a prior request.
395
+ * @returns A function that emits the completion notification when awaited.
396
+ */
397
+ createElicitationCompletionNotifier(elicitationId, options) {
398
+ if (!this._clientCapabilities?.elicitation?.url) {
399
+ throw new Error('Client does not support URL elicitation (required for notifications/elicitation/complete)');
400
+ }
401
+ return () => this.notification({
402
+ method: 'notifications/elicitation/complete',
403
+ params: {
404
+ elicitationId
405
+ }
406
+ }, options);
407
+ }
408
+ async listRoots(params, options) {
409
+ return this.request({ method: 'roots/list', params }, types_js_1.ListRootsResultSchema, options);
410
+ }
411
+ /**
412
+ * Sends a logging message to the client, if connected.
413
+ * Note: You only need to send the parameters object, not the entire JSON RPC message
414
+ * @see LoggingMessageNotification
415
+ * @param params
416
+ * @param sessionId optional for stateless and backward compatibility
417
+ */
418
+ async sendLoggingMessage(params, sessionId) {
419
+ if (this._capabilities.logging) {
420
+ if (!this.isMessageIgnored(params.level, sessionId)) {
421
+ return this.notification({ method: 'notifications/message', params });
422
+ }
423
+ }
424
+ }
425
+ async sendResourceUpdated(params) {
426
+ return this.notification({
427
+ method: 'notifications/resources/updated',
428
+ params
429
+ });
430
+ }
431
+ async sendResourceListChanged() {
432
+ return this.notification({
433
+ method: 'notifications/resources/list_changed'
434
+ });
435
+ }
436
+ async sendToolListChanged() {
437
+ return this.notification({ method: 'notifications/tools/list_changed' });
438
+ }
439
+ async sendPromptListChanged() {
440
+ return this.notification({ method: 'notifications/prompts/list_changed' });
441
+ }
442
+ }
443
+ exports.Server = Server;
444
+ //# sourceMappingURL=index.js.map