@ctxprotocol/sdk 0.6.0 → 0.7.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.
@@ -141,10 +141,101 @@ interface ExecutionResult<T = unknown> {
141
141
  /** Execution duration in milliseconds */
142
142
  durationMs: number;
143
143
  }
144
+ /**
145
+ * Options for the agentic query endpoint (pay-per-response).
146
+ *
147
+ * Unlike `execute()` which calls a single tool once, `query()` sends a
148
+ * natural-language question and lets the server handle tool discovery,
149
+ * multi-tool orchestration, self-healing retries, and AI synthesis.
150
+ * One flat fee covers up to 100 MCP skill calls per tool.
151
+ */
152
+ interface QueryOptions {
153
+ /** The natural-language question to answer */
154
+ query: string;
155
+ /**
156
+ * Optional tool IDs to use. When omitted the server discovers tools
157
+ * automatically (Auto Mode). When provided, only these tools are used
158
+ * (Manual Mode).
159
+ */
160
+ tools?: string[];
161
+ }
162
+ /**
163
+ * Information about a tool that was used during a query response
164
+ */
165
+ interface QueryToolUsage {
166
+ /** Tool ID */
167
+ id: string;
168
+ /** Tool name */
169
+ name: string;
170
+ /** Number of MCP skill calls made for this tool */
171
+ skillCalls: number;
172
+ }
173
+ /**
174
+ * Cost breakdown for a query response.
175
+ * All values are strings representing USD amounts.
176
+ */
177
+ interface QueryCost {
178
+ /** AI model inference cost */
179
+ modelCostUsd: string;
180
+ /** Sum of all tool fees */
181
+ toolCostUsd: string;
182
+ /** Total cost (model + tools) */
183
+ totalCostUsd: string;
184
+ }
185
+ /**
186
+ * The resolved result of a pay-per-response query
187
+ */
188
+ interface QueryResult {
189
+ /** The AI-synthesized response text */
190
+ response: string;
191
+ /** Tools that were used to answer the query */
192
+ toolsUsed: QueryToolUsage[];
193
+ /** Cost breakdown */
194
+ cost: QueryCost;
195
+ /** Total duration in milliseconds */
196
+ durationMs: number;
197
+ }
198
+ /**
199
+ * Successful response from the /api/v1/query endpoint
200
+ */
201
+ interface QueryApiSuccessResponse {
202
+ success: true;
203
+ response: string;
204
+ toolsUsed: QueryToolUsage[];
205
+ cost: QueryCost;
206
+ durationMs: number;
207
+ }
208
+ /**
209
+ * Raw API response from the query endpoint
210
+ */
211
+ type QueryApiResponse = QueryApiSuccessResponse | ExecuteApiErrorResponse;
212
+ /** Emitted when a tool starts or changes execution status */
213
+ interface QueryStreamToolStatusEvent {
214
+ type: "tool-status";
215
+ tool: {
216
+ id: string;
217
+ name: string;
218
+ };
219
+ status: string;
220
+ }
221
+ /** Emitted for each chunk of the AI response text */
222
+ interface QueryStreamTextDeltaEvent {
223
+ type: "text-delta";
224
+ delta: string;
225
+ }
226
+ /** Emitted when the full response is complete */
227
+ interface QueryStreamDoneEvent {
228
+ type: "done";
229
+ result: QueryResult;
230
+ }
231
+ /**
232
+ * Union of all events emitted during a streaming query
233
+ */
234
+ type QueryStreamEvent = QueryStreamToolStatusEvent | QueryStreamTextDeltaEvent | QueryStreamDoneEvent;
144
235
  /**
145
236
  * Specific error codes returned by the Context Protocol API
146
237
  */
147
- type ContextErrorCode = "unauthorized" | "no_wallet" | "insufficient_allowance" | "payment_failed" | "execution_failed";
238
+ type ContextErrorCode = "unauthorized" | "no_wallet" | "insufficient_allowance" | "payment_failed" | "execution_failed" | "query_failed";
148
239
  /**
149
240
  * Error thrown by the Context Protocol client
150
241
  */
@@ -206,8 +297,8 @@ declare class Tools {
206
297
  * @returns The execution result with the tool's output data
207
298
  *
208
299
  * @throws {ContextError} With code `no_wallet` if wallet not set up
209
- * @throws {ContextError} With code `insufficient_allowance` if Auto Pay not enabled
210
- * @throws {ContextError} With code `payment_failed` if on-chain payment fails
300
+ * @throws {ContextError} With code `insufficient_allowance` if spending cap not set
301
+ * @throws {ContextError} With code `payment_failed` if payment settlement fails
211
302
  * @throws {ContextError} With code `execution_failed` if tool execution fails
212
303
  *
213
304
  * @example
@@ -230,6 +321,85 @@ declare class Tools {
230
321
  execute<T = unknown>(options: ExecuteOptions): Promise<ExecutionResult<T>>;
231
322
  }
232
323
 
324
+ /**
325
+ * Query resource for pay-per-response agentic queries.
326
+ *
327
+ * Unlike `tools.execute()` which calls a single tool once (pay-per-request),
328
+ * the Query resource sends a natural-language question and lets the server
329
+ * handle tool discovery, multi-tool orchestration, self-healing retries,
330
+ * completeness checks, and AI synthesis — all for one flat fee.
331
+ *
332
+ * This is the "prepared meal" vs "raw ingredients" distinction:
333
+ * - `tools.execute()` = raw data, full control, predictable cost
334
+ * - `query.run()` / `query.stream()` = curated intelligence, one payment
335
+ */
336
+ declare class Query {
337
+ private client;
338
+ constructor(client: ContextClient);
339
+ /**
340
+ * Run an agentic query and wait for the full response.
341
+ *
342
+ * The server discovers relevant tools (or uses the ones you specify),
343
+ * executes the full agentic pipeline (up to 100 MCP calls per tool),
344
+ * and returns an AI-synthesized answer. Payment is settled after
345
+ * successful execution via deferred settlement.
346
+ *
347
+ * @param options - Query options or a plain string question
348
+ * @returns The complete query result with response text, tools used, and cost
349
+ *
350
+ * @throws {ContextError} With code `no_wallet` if wallet not set up
351
+ * @throws {ContextError} With code `insufficient_allowance` if spending cap not set
352
+ * @throws {ContextError} With code `payment_failed` if payment settlement fails
353
+ * @throws {ContextError} With code `execution_failed` if the agentic pipeline fails
354
+ *
355
+ * @example
356
+ * ```typescript
357
+ * // Simple question — server discovers tools automatically
358
+ * const answer = await client.query.run("What are the top whale movements on Base?");
359
+ * console.log(answer.response); // AI-synthesized answer
360
+ * console.log(answer.toolsUsed); // Which tools were used
361
+ * console.log(answer.cost); // Cost breakdown
362
+ *
363
+ * // With specific tools (Manual Mode)
364
+ * const answer = await client.query.run({
365
+ * query: "Analyze whale activity",
366
+ * tools: ["tool-uuid-1", "tool-uuid-2"],
367
+ * });
368
+ * ```
369
+ */
370
+ run(options: QueryOptions | string): Promise<QueryResult>;
371
+ /**
372
+ * Run an agentic query with streaming. Returns an async iterable that
373
+ * yields events as the server processes the query in real-time.
374
+ *
375
+ * Event types:
376
+ * - `tool-status` — A tool started executing or changed status
377
+ * - `text-delta` — A chunk of the AI response text
378
+ * - `done` — The full response is complete (includes final `QueryResult`)
379
+ *
380
+ * @param options - Query options or a plain string question
381
+ * @returns An async iterable of stream events
382
+ *
383
+ * @example
384
+ * ```typescript
385
+ * for await (const event of client.query.stream("What are the top whale movements?")) {
386
+ * switch (event.type) {
387
+ * case "tool-status":
388
+ * console.log(`Tool ${event.tool.name}: ${event.status}`);
389
+ * break;
390
+ * case "text-delta":
391
+ * process.stdout.write(event.delta);
392
+ * break;
393
+ * case "done":
394
+ * console.log("\nCost:", event.result.cost.totalCostUsd);
395
+ * break;
396
+ * }
397
+ * }
398
+ * ```
399
+ */
400
+ stream(options: QueryOptions | string): AsyncGenerator<QueryStreamEvent>;
401
+ }
402
+
233
403
  /**
234
404
  * The official TypeScript client for the Context Protocol.
235
405
  *
@@ -243,15 +413,16 @@ declare class Tools {
243
413
  * apiKey: "sk_live_..."
244
414
  * });
245
415
  *
246
- * // Discover tools
247
- * const tools = await client.discovery.search("gas prices");
248
- *
249
- * // Execute a tool method
416
+ * // Pay-per-request: Execute a specific tool
250
417
  * const result = await client.tools.execute({
251
- * toolId: tools[0].id,
252
- * toolName: tools[0].mcpTools[0].name,
418
+ * toolId: "tool-uuid",
419
+ * toolName: "get_gas_prices",
253
420
  * args: { chainId: 1 }
254
421
  * });
422
+ *
423
+ * // Pay-per-response: Ask a question, get a curated answer
424
+ * const answer = await client.query.run("What are the top whale movements on Base?");
425
+ * console.log(answer.response);
255
426
  * ```
256
427
  */
257
428
  declare class ContextClient {
@@ -263,9 +434,17 @@ declare class ContextClient {
263
434
  */
264
435
  readonly discovery: Discovery;
265
436
  /**
266
- * Tools resource for executing tools
437
+ * Tools resource for executing tools (pay-per-request)
267
438
  */
268
439
  readonly tools: Tools;
440
+ /**
441
+ * Query resource for agentic queries (pay-per-response).
442
+ *
443
+ * Unlike `tools.execute()` which calls a single tool once, `query` sends
444
+ * a natural-language question and lets the server handle tool discovery,
445
+ * multi-tool orchestration, self-healing, and AI synthesis — one flat fee.
446
+ */
447
+ readonly query: Query;
269
448
  /**
270
449
  * Creates a new Context Protocol client
271
450
  *
@@ -286,6 +465,13 @@ declare class ContextClient {
286
465
  * @internal
287
466
  */
288
467
  _fetch<T>(endpoint: string, options?: RequestInit): Promise<T>;
468
+ /**
469
+ * Internal method for making authenticated HTTP requests that returns
470
+ * the raw Response object. Used for streaming endpoints (SSE).
471
+ *
472
+ * @internal
473
+ */
474
+ _fetchRaw(endpoint: string, options?: RequestInit): Promise<Response>;
289
475
  }
290
476
 
291
- export { ContextClient, type ContextClientOptions, ContextError, type ContextErrorCode, Discovery, type ExecuteApiErrorResponse, type ExecuteApiResponse, type ExecuteApiSuccessResponse, type ExecuteOptions, type ExecutionResult, type McpTool, type SearchOptions, type SearchResponse, type Tool, Tools };
477
+ export { ContextClient, type ContextClientOptions, ContextError, type ContextErrorCode, Discovery, type ExecuteApiErrorResponse, type ExecuteApiResponse, type ExecuteApiSuccessResponse, type ExecuteOptions, type ExecutionResult, type McpTool, Query, type QueryApiResponse, type QueryApiSuccessResponse, type QueryCost, type QueryOptions, type QueryResult, type QueryStreamDoneEvent, type QueryStreamEvent, type QueryStreamTextDeltaEvent, type QueryStreamToolStatusEvent, type QueryToolUsage, type SearchOptions, type SearchResponse, type Tool, Tools };
@@ -141,10 +141,101 @@ interface ExecutionResult<T = unknown> {
141
141
  /** Execution duration in milliseconds */
142
142
  durationMs: number;
143
143
  }
144
+ /**
145
+ * Options for the agentic query endpoint (pay-per-response).
146
+ *
147
+ * Unlike `execute()` which calls a single tool once, `query()` sends a
148
+ * natural-language question and lets the server handle tool discovery,
149
+ * multi-tool orchestration, self-healing retries, and AI synthesis.
150
+ * One flat fee covers up to 100 MCP skill calls per tool.
151
+ */
152
+ interface QueryOptions {
153
+ /** The natural-language question to answer */
154
+ query: string;
155
+ /**
156
+ * Optional tool IDs to use. When omitted the server discovers tools
157
+ * automatically (Auto Mode). When provided, only these tools are used
158
+ * (Manual Mode).
159
+ */
160
+ tools?: string[];
161
+ }
162
+ /**
163
+ * Information about a tool that was used during a query response
164
+ */
165
+ interface QueryToolUsage {
166
+ /** Tool ID */
167
+ id: string;
168
+ /** Tool name */
169
+ name: string;
170
+ /** Number of MCP skill calls made for this tool */
171
+ skillCalls: number;
172
+ }
173
+ /**
174
+ * Cost breakdown for a query response.
175
+ * All values are strings representing USD amounts.
176
+ */
177
+ interface QueryCost {
178
+ /** AI model inference cost */
179
+ modelCostUsd: string;
180
+ /** Sum of all tool fees */
181
+ toolCostUsd: string;
182
+ /** Total cost (model + tools) */
183
+ totalCostUsd: string;
184
+ }
185
+ /**
186
+ * The resolved result of a pay-per-response query
187
+ */
188
+ interface QueryResult {
189
+ /** The AI-synthesized response text */
190
+ response: string;
191
+ /** Tools that were used to answer the query */
192
+ toolsUsed: QueryToolUsage[];
193
+ /** Cost breakdown */
194
+ cost: QueryCost;
195
+ /** Total duration in milliseconds */
196
+ durationMs: number;
197
+ }
198
+ /**
199
+ * Successful response from the /api/v1/query endpoint
200
+ */
201
+ interface QueryApiSuccessResponse {
202
+ success: true;
203
+ response: string;
204
+ toolsUsed: QueryToolUsage[];
205
+ cost: QueryCost;
206
+ durationMs: number;
207
+ }
208
+ /**
209
+ * Raw API response from the query endpoint
210
+ */
211
+ type QueryApiResponse = QueryApiSuccessResponse | ExecuteApiErrorResponse;
212
+ /** Emitted when a tool starts or changes execution status */
213
+ interface QueryStreamToolStatusEvent {
214
+ type: "tool-status";
215
+ tool: {
216
+ id: string;
217
+ name: string;
218
+ };
219
+ status: string;
220
+ }
221
+ /** Emitted for each chunk of the AI response text */
222
+ interface QueryStreamTextDeltaEvent {
223
+ type: "text-delta";
224
+ delta: string;
225
+ }
226
+ /** Emitted when the full response is complete */
227
+ interface QueryStreamDoneEvent {
228
+ type: "done";
229
+ result: QueryResult;
230
+ }
231
+ /**
232
+ * Union of all events emitted during a streaming query
233
+ */
234
+ type QueryStreamEvent = QueryStreamToolStatusEvent | QueryStreamTextDeltaEvent | QueryStreamDoneEvent;
144
235
  /**
145
236
  * Specific error codes returned by the Context Protocol API
146
237
  */
147
- type ContextErrorCode = "unauthorized" | "no_wallet" | "insufficient_allowance" | "payment_failed" | "execution_failed";
238
+ type ContextErrorCode = "unauthorized" | "no_wallet" | "insufficient_allowance" | "payment_failed" | "execution_failed" | "query_failed";
148
239
  /**
149
240
  * Error thrown by the Context Protocol client
150
241
  */
@@ -206,8 +297,8 @@ declare class Tools {
206
297
  * @returns The execution result with the tool's output data
207
298
  *
208
299
  * @throws {ContextError} With code `no_wallet` if wallet not set up
209
- * @throws {ContextError} With code `insufficient_allowance` if Auto Pay not enabled
210
- * @throws {ContextError} With code `payment_failed` if on-chain payment fails
300
+ * @throws {ContextError} With code `insufficient_allowance` if spending cap not set
301
+ * @throws {ContextError} With code `payment_failed` if payment settlement fails
211
302
  * @throws {ContextError} With code `execution_failed` if tool execution fails
212
303
  *
213
304
  * @example
@@ -230,6 +321,85 @@ declare class Tools {
230
321
  execute<T = unknown>(options: ExecuteOptions): Promise<ExecutionResult<T>>;
231
322
  }
232
323
 
324
+ /**
325
+ * Query resource for pay-per-response agentic queries.
326
+ *
327
+ * Unlike `tools.execute()` which calls a single tool once (pay-per-request),
328
+ * the Query resource sends a natural-language question and lets the server
329
+ * handle tool discovery, multi-tool orchestration, self-healing retries,
330
+ * completeness checks, and AI synthesis — all for one flat fee.
331
+ *
332
+ * This is the "prepared meal" vs "raw ingredients" distinction:
333
+ * - `tools.execute()` = raw data, full control, predictable cost
334
+ * - `query.run()` / `query.stream()` = curated intelligence, one payment
335
+ */
336
+ declare class Query {
337
+ private client;
338
+ constructor(client: ContextClient);
339
+ /**
340
+ * Run an agentic query and wait for the full response.
341
+ *
342
+ * The server discovers relevant tools (or uses the ones you specify),
343
+ * executes the full agentic pipeline (up to 100 MCP calls per tool),
344
+ * and returns an AI-synthesized answer. Payment is settled after
345
+ * successful execution via deferred settlement.
346
+ *
347
+ * @param options - Query options or a plain string question
348
+ * @returns The complete query result with response text, tools used, and cost
349
+ *
350
+ * @throws {ContextError} With code `no_wallet` if wallet not set up
351
+ * @throws {ContextError} With code `insufficient_allowance` if spending cap not set
352
+ * @throws {ContextError} With code `payment_failed` if payment settlement fails
353
+ * @throws {ContextError} With code `execution_failed` if the agentic pipeline fails
354
+ *
355
+ * @example
356
+ * ```typescript
357
+ * // Simple question — server discovers tools automatically
358
+ * const answer = await client.query.run("What are the top whale movements on Base?");
359
+ * console.log(answer.response); // AI-synthesized answer
360
+ * console.log(answer.toolsUsed); // Which tools were used
361
+ * console.log(answer.cost); // Cost breakdown
362
+ *
363
+ * // With specific tools (Manual Mode)
364
+ * const answer = await client.query.run({
365
+ * query: "Analyze whale activity",
366
+ * tools: ["tool-uuid-1", "tool-uuid-2"],
367
+ * });
368
+ * ```
369
+ */
370
+ run(options: QueryOptions | string): Promise<QueryResult>;
371
+ /**
372
+ * Run an agentic query with streaming. Returns an async iterable that
373
+ * yields events as the server processes the query in real-time.
374
+ *
375
+ * Event types:
376
+ * - `tool-status` — A tool started executing or changed status
377
+ * - `text-delta` — A chunk of the AI response text
378
+ * - `done` — The full response is complete (includes final `QueryResult`)
379
+ *
380
+ * @param options - Query options or a plain string question
381
+ * @returns An async iterable of stream events
382
+ *
383
+ * @example
384
+ * ```typescript
385
+ * for await (const event of client.query.stream("What are the top whale movements?")) {
386
+ * switch (event.type) {
387
+ * case "tool-status":
388
+ * console.log(`Tool ${event.tool.name}: ${event.status}`);
389
+ * break;
390
+ * case "text-delta":
391
+ * process.stdout.write(event.delta);
392
+ * break;
393
+ * case "done":
394
+ * console.log("\nCost:", event.result.cost.totalCostUsd);
395
+ * break;
396
+ * }
397
+ * }
398
+ * ```
399
+ */
400
+ stream(options: QueryOptions | string): AsyncGenerator<QueryStreamEvent>;
401
+ }
402
+
233
403
  /**
234
404
  * The official TypeScript client for the Context Protocol.
235
405
  *
@@ -243,15 +413,16 @@ declare class Tools {
243
413
  * apiKey: "sk_live_..."
244
414
  * });
245
415
  *
246
- * // Discover tools
247
- * const tools = await client.discovery.search("gas prices");
248
- *
249
- * // Execute a tool method
416
+ * // Pay-per-request: Execute a specific tool
250
417
  * const result = await client.tools.execute({
251
- * toolId: tools[0].id,
252
- * toolName: tools[0].mcpTools[0].name,
418
+ * toolId: "tool-uuid",
419
+ * toolName: "get_gas_prices",
253
420
  * args: { chainId: 1 }
254
421
  * });
422
+ *
423
+ * // Pay-per-response: Ask a question, get a curated answer
424
+ * const answer = await client.query.run("What are the top whale movements on Base?");
425
+ * console.log(answer.response);
255
426
  * ```
256
427
  */
257
428
  declare class ContextClient {
@@ -263,9 +434,17 @@ declare class ContextClient {
263
434
  */
264
435
  readonly discovery: Discovery;
265
436
  /**
266
- * Tools resource for executing tools
437
+ * Tools resource for executing tools (pay-per-request)
267
438
  */
268
439
  readonly tools: Tools;
440
+ /**
441
+ * Query resource for agentic queries (pay-per-response).
442
+ *
443
+ * Unlike `tools.execute()` which calls a single tool once, `query` sends
444
+ * a natural-language question and lets the server handle tool discovery,
445
+ * multi-tool orchestration, self-healing, and AI synthesis — one flat fee.
446
+ */
447
+ readonly query: Query;
269
448
  /**
270
449
  * Creates a new Context Protocol client
271
450
  *
@@ -286,6 +465,13 @@ declare class ContextClient {
286
465
  * @internal
287
466
  */
288
467
  _fetch<T>(endpoint: string, options?: RequestInit): Promise<T>;
468
+ /**
469
+ * Internal method for making authenticated HTTP requests that returns
470
+ * the raw Response object. Used for streaming endpoints (SSE).
471
+ *
472
+ * @internal
473
+ */
474
+ _fetchRaw(endpoint: string, options?: RequestInit): Promise<Response>;
289
475
  }
290
476
 
291
- export { ContextClient, type ContextClientOptions, ContextError, type ContextErrorCode, Discovery, type ExecuteApiErrorResponse, type ExecuteApiResponse, type ExecuteApiSuccessResponse, type ExecuteOptions, type ExecutionResult, type McpTool, type SearchOptions, type SearchResponse, type Tool, Tools };
477
+ export { ContextClient, type ContextClientOptions, ContextError, type ContextErrorCode, Discovery, type ExecuteApiErrorResponse, type ExecuteApiResponse, type ExecuteApiSuccessResponse, type ExecuteOptions, type ExecutionResult, type McpTool, Query, type QueryApiResponse, type QueryApiSuccessResponse, type QueryCost, type QueryOptions, type QueryResult, type QueryStreamDoneEvent, type QueryStreamEvent, type QueryStreamTextDeltaEvent, type QueryStreamToolStatusEvent, type QueryToolUsage, type SearchOptions, type SearchResponse, type Tool, Tools };