@qwen-code/sdk 0.1.0-preview.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.
@@ -0,0 +1,957 @@
1
+ // Generated by dts-bundle-generator v9.5.1
2
+
3
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
4
+ import { CallToolResultSchema } from '@modelcontextprotocol/sdk/types.js';
5
+ import { ZodObject, ZodRawShape, ZodTypeAny, z } from 'zod';
6
+
7
+ export interface Annotation {
8
+ type: string;
9
+ value: string;
10
+ }
11
+ export interface Usage {
12
+ input_tokens: number;
13
+ output_tokens: number;
14
+ cache_creation_input_tokens?: number;
15
+ cache_read_input_tokens?: number;
16
+ total_tokens?: number;
17
+ }
18
+ export interface ExtendedUsage extends Usage {
19
+ server_tool_use?: {
20
+ web_search_requests: number;
21
+ };
22
+ service_tier?: string;
23
+ cache_creation?: {
24
+ ephemeral_1h_input_tokens: number;
25
+ ephemeral_5m_input_tokens: number;
26
+ };
27
+ }
28
+ export interface ModelUsage {
29
+ inputTokens: number;
30
+ outputTokens: number;
31
+ cacheReadInputTokens: number;
32
+ cacheCreationInputTokens: number;
33
+ webSearchRequests: number;
34
+ contextWindow: number;
35
+ }
36
+ export interface CLIPermissionDenial {
37
+ tool_name: string;
38
+ tool_use_id: string;
39
+ tool_input: unknown;
40
+ }
41
+ export interface TextBlock {
42
+ type: "text";
43
+ text: string;
44
+ annotations?: Annotation[];
45
+ }
46
+ export interface ThinkingBlock {
47
+ type: "thinking";
48
+ thinking: string;
49
+ signature?: string;
50
+ annotations?: Annotation[];
51
+ }
52
+ export interface ToolUseBlock {
53
+ type: "tool_use";
54
+ id: string;
55
+ name: string;
56
+ input: unknown;
57
+ annotations?: Annotation[];
58
+ }
59
+ export interface ToolResultBlock {
60
+ type: "tool_result";
61
+ tool_use_id: string;
62
+ content?: string | ContentBlock[];
63
+ is_error?: boolean;
64
+ annotations?: Annotation[];
65
+ }
66
+ export type ContentBlock = TextBlock | ThinkingBlock | ToolUseBlock | ToolResultBlock;
67
+ export interface APIUserMessage {
68
+ role: "user";
69
+ content: string | ContentBlock[];
70
+ }
71
+ export interface APIAssistantMessage {
72
+ id: string;
73
+ type: "message";
74
+ role: "assistant";
75
+ model: string;
76
+ content: ContentBlock[];
77
+ stop_reason?: string | null;
78
+ usage: Usage;
79
+ }
80
+ export interface SDKUserMessage {
81
+ type: "user";
82
+ uuid?: string;
83
+ session_id: string;
84
+ message: APIUserMessage;
85
+ parent_tool_use_id: string | null;
86
+ options?: Record<string, unknown>;
87
+ }
88
+ export interface SDKAssistantMessage {
89
+ type: "assistant";
90
+ uuid: string;
91
+ session_id: string;
92
+ message: APIAssistantMessage;
93
+ parent_tool_use_id: string | null;
94
+ }
95
+ export interface SDKSystemMessage {
96
+ type: "system";
97
+ subtype: string;
98
+ uuid: string;
99
+ session_id: string;
100
+ data?: unknown;
101
+ cwd?: string;
102
+ tools?: string[];
103
+ mcp_servers?: Array<{
104
+ name: string;
105
+ status: string;
106
+ }>;
107
+ model?: string;
108
+ permission_mode?: string;
109
+ slash_commands?: string[];
110
+ qwen_code_version?: string;
111
+ output_style?: string;
112
+ agents?: string[];
113
+ skills?: string[];
114
+ capabilities?: Record<string, unknown>;
115
+ compact_metadata?: {
116
+ trigger: "manual" | "auto";
117
+ pre_tokens: number;
118
+ };
119
+ }
120
+ export interface SDKResultMessageSuccess {
121
+ type: "result";
122
+ subtype: "success";
123
+ uuid: string;
124
+ session_id: string;
125
+ is_error: false;
126
+ duration_ms: number;
127
+ duration_api_ms: number;
128
+ num_turns: number;
129
+ result: string;
130
+ usage: ExtendedUsage;
131
+ modelUsage?: Record<string, ModelUsage>;
132
+ permission_denials: CLIPermissionDenial[];
133
+ [key: string]: unknown;
134
+ }
135
+ export interface SDKResultMessageError {
136
+ type: "result";
137
+ subtype: "error_max_turns" | "error_during_execution";
138
+ uuid: string;
139
+ session_id: string;
140
+ is_error: true;
141
+ duration_ms: number;
142
+ duration_api_ms: number;
143
+ num_turns: number;
144
+ usage: ExtendedUsage;
145
+ modelUsage?: Record<string, ModelUsage>;
146
+ permission_denials: CLIPermissionDenial[];
147
+ error?: {
148
+ type?: string;
149
+ message: string;
150
+ [key: string]: unknown;
151
+ };
152
+ [key: string]: unknown;
153
+ }
154
+ export type SDKResultMessage = SDKResultMessageSuccess | SDKResultMessageError;
155
+ export interface MessageStartStreamEvent {
156
+ type: "message_start";
157
+ message: {
158
+ id: string;
159
+ role: "assistant";
160
+ model: string;
161
+ };
162
+ }
163
+ export interface ContentBlockStartEvent {
164
+ type: "content_block_start";
165
+ index: number;
166
+ content_block: ContentBlock;
167
+ }
168
+ export type ContentBlockDelta = {
169
+ type: "text_delta";
170
+ text: string;
171
+ } | {
172
+ type: "thinking_delta";
173
+ thinking: string;
174
+ } | {
175
+ type: "input_json_delta";
176
+ partial_json: string;
177
+ };
178
+ export interface ContentBlockDeltaEvent {
179
+ type: "content_block_delta";
180
+ index: number;
181
+ delta: ContentBlockDelta;
182
+ }
183
+ export interface ContentBlockStopEvent {
184
+ type: "content_block_stop";
185
+ index: number;
186
+ }
187
+ export interface MessageStopStreamEvent {
188
+ type: "message_stop";
189
+ }
190
+ export type StreamEvent = MessageStartStreamEvent | ContentBlockStartEvent | ContentBlockDeltaEvent | ContentBlockStopEvent | MessageStopStreamEvent;
191
+ export interface SDKPartialAssistantMessage {
192
+ type: "stream_event";
193
+ uuid: string;
194
+ session_id: string;
195
+ event: StreamEvent;
196
+ parent_tool_use_id: string | null;
197
+ }
198
+ export type PermissionMode = "default" | "plan" | "auto-edit" | "yolo";
199
+ /**
200
+ * TODO: Align with `ToolCallConfirmationDetails`
201
+ */
202
+ export interface PermissionSuggestion {
203
+ type: "allow" | "deny" | "modify";
204
+ label: string;
205
+ description?: string;
206
+ modifiedInput?: unknown;
207
+ }
208
+ export interface HookRegistration {
209
+ event: string;
210
+ callback_id: string;
211
+ }
212
+ export interface CLIControlInterruptRequest {
213
+ subtype: "interrupt";
214
+ }
215
+ export interface CLIControlPermissionRequest {
216
+ subtype: "can_use_tool";
217
+ tool_name: string;
218
+ tool_use_id: string;
219
+ input: unknown;
220
+ permission_suggestions: PermissionSuggestion[] | null;
221
+ blocked_path: string | null;
222
+ }
223
+ declare enum AuthProviderType {
224
+ DYNAMIC_DISCOVERY = "dynamic_discovery",
225
+ GOOGLE_CREDENTIALS = "google_credentials",
226
+ SERVICE_ACCOUNT_IMPERSONATION = "service_account_impersonation"
227
+ }
228
+ export interface MCPServerConfig {
229
+ command?: string;
230
+ args?: string[];
231
+ env?: Record<string, string>;
232
+ cwd?: string;
233
+ url?: string;
234
+ httpUrl?: string;
235
+ headers?: Record<string, string>;
236
+ tcp?: string;
237
+ timeout?: number;
238
+ trust?: boolean;
239
+ description?: string;
240
+ includeTools?: string[];
241
+ excludeTools?: string[];
242
+ extensionName?: string;
243
+ oauth?: Record<string, unknown>;
244
+ authProviderType?: AuthProviderType;
245
+ targetAudience?: string;
246
+ targetServiceAccount?: string;
247
+ }
248
+ /**
249
+ * SDK MCP Server configuration
250
+ *
251
+ * SDK MCP servers run in the SDK process and are connected via in-memory transport.
252
+ * Tool calls are routed through the control plane between SDK and CLI.
253
+ */
254
+ export interface SDKMcpServerConfig {
255
+ /**
256
+ * Type identifier for SDK MCP servers
257
+ */
258
+ type: "sdk";
259
+ /**
260
+ * Server name for identification and routing
261
+ */
262
+ name: string;
263
+ /**
264
+ * The MCP Server instance created by createSdkMcpServer()
265
+ */
266
+ instance: McpServer;
267
+ }
268
+ /**
269
+ * Wire format for SDK MCP servers sent to the CLI
270
+ */
271
+ export type WireSDKMcpServerConfig = Omit<SDKMcpServerConfig, "instance">;
272
+ export interface CLIControlInitializeRequest {
273
+ subtype: "initialize";
274
+ hooks?: HookRegistration[] | null;
275
+ /**
276
+ * SDK MCP servers config
277
+ * These are MCP servers running in the SDK process, connected via control plane.
278
+ * External MCP servers are configured separately in settings, not via initialization.
279
+ */
280
+ sdkMcpServers?: Record<string, WireSDKMcpServerConfig>;
281
+ /**
282
+ * External MCP servers that should be managed by the CLI.
283
+ */
284
+ mcpServers?: Record<string, MCPServerConfig>;
285
+ agents?: SubagentConfig[];
286
+ }
287
+ export interface CLIControlSetPermissionModeRequest {
288
+ subtype: "set_permission_mode";
289
+ mode: PermissionMode;
290
+ }
291
+ export interface CLIHookCallbackRequest {
292
+ subtype: "hook_callback";
293
+ callback_id: string;
294
+ input: unknown;
295
+ tool_use_id: string | null;
296
+ }
297
+ export interface CLIControlMcpMessageRequest {
298
+ subtype: "mcp_message";
299
+ server_name: string;
300
+ message: {
301
+ jsonrpc?: string;
302
+ method: string;
303
+ params?: Record<string, unknown>;
304
+ id?: string | number | null;
305
+ };
306
+ }
307
+ export interface CLIControlSetModelRequest {
308
+ subtype: "set_model";
309
+ model: string;
310
+ }
311
+ export interface CLIControlMcpStatusRequest {
312
+ subtype: "mcp_server_status";
313
+ }
314
+ export interface CLIControlSupportedCommandsRequest {
315
+ subtype: "supported_commands";
316
+ }
317
+ export type ControlRequestPayload = CLIControlInterruptRequest | CLIControlPermissionRequest | CLIControlInitializeRequest | CLIControlSetPermissionModeRequest | CLIHookCallbackRequest | CLIControlMcpMessageRequest | CLIControlSetModelRequest | CLIControlMcpStatusRequest | CLIControlSupportedCommandsRequest;
318
+ export interface CLIControlRequest {
319
+ type: "control_request";
320
+ request_id: string;
321
+ request: ControlRequestPayload;
322
+ }
323
+ export interface ControlResponse {
324
+ subtype: "success";
325
+ request_id: string;
326
+ response: unknown;
327
+ }
328
+ export interface ControlErrorResponse {
329
+ subtype: "error";
330
+ request_id: string;
331
+ error: string | {
332
+ message: string;
333
+ [key: string]: unknown;
334
+ };
335
+ }
336
+ export interface CLIControlResponse {
337
+ type: "control_response";
338
+ response: ControlResponse | ControlErrorResponse;
339
+ }
340
+ export interface ControlCancelRequest {
341
+ type: "control_cancel_request";
342
+ request_id?: string;
343
+ }
344
+ export type ControlMessage = CLIControlRequest | CLIControlResponse | ControlCancelRequest;
345
+ /**
346
+ * Union of all SDK message types
347
+ */
348
+ export type SDKMessage = SDKUserMessage | SDKAssistantMessage | SDKSystemMessage | SDKResultMessage | SDKPartialAssistantMessage;
349
+ export declare function isSDKUserMessage(msg: any): msg is SDKUserMessage;
350
+ export declare function isSDKAssistantMessage(msg: any): msg is SDKAssistantMessage;
351
+ export declare function isSDKSystemMessage(msg: any): msg is SDKSystemMessage;
352
+ export declare function isSDKResultMessage(msg: any): msg is SDKResultMessage;
353
+ export declare function isSDKPartialAssistantMessage(msg: any): msg is SDKPartialAssistantMessage;
354
+ export declare function isControlRequest(msg: any): msg is CLIControlRequest;
355
+ export declare function isControlResponse(msg: any): msg is CLIControlResponse;
356
+ export declare function isControlCancel(msg: any): msg is ControlCancelRequest;
357
+ export type SubagentLevel = "session";
358
+ export interface ModelConfig {
359
+ model?: string;
360
+ temp?: number;
361
+ top_p?: number;
362
+ }
363
+ export interface RunConfig {
364
+ max_time_minutes?: number;
365
+ max_turns?: number;
366
+ }
367
+ export interface SubagentConfig {
368
+ name: string;
369
+ description: string;
370
+ tools?: string[];
371
+ systemPrompt: string;
372
+ level: SubagentLevel;
373
+ filePath?: string;
374
+ modelConfig?: Partial<ModelConfig>;
375
+ runConfig?: Partial<RunConfig>;
376
+ color?: string;
377
+ readonly isBuiltin?: boolean;
378
+ }
379
+ /**
380
+ * Transport interface for SDK-CLI communication
381
+ *
382
+ * The Transport abstraction enables communication between SDK and CLI via different mechanisms:
383
+ * - ProcessTransport: Local subprocess via stdin/stdout (initial implementation)
384
+ * - HttpTransport: Remote CLI via HTTP (future)
385
+ * - WebSocketTransport: Remote CLI via WebSocket (future)
386
+ */
387
+ export interface Transport {
388
+ close(): Promise<void>;
389
+ waitForExit(): Promise<void>;
390
+ write(message: string): void;
391
+ readMessages(): AsyncGenerator<unknown, void, unknown>;
392
+ readonly isReady: boolean;
393
+ readonly exitError: Error | null;
394
+ }
395
+ export type ToolInput = Record<string, unknown>;
396
+ export type CanUseTool = (toolName: string, input: ToolInput, options: {
397
+ signal: AbortSignal;
398
+ suggestions?: PermissionSuggestion[] | null;
399
+ }) => Promise<PermissionResult>;
400
+ export type PermissionResult = {
401
+ behavior: "allow";
402
+ updatedInput: ToolInput;
403
+ } | {
404
+ behavior: "deny";
405
+ message: string;
406
+ interrupt?: boolean;
407
+ };
408
+ /**
409
+ * OAuth configuration for MCP servers
410
+ */
411
+ export interface McpOAuthConfig {
412
+ enabled?: boolean;
413
+ clientId?: string;
414
+ clientSecret?: string;
415
+ scopes?: string[];
416
+ redirectUri?: string;
417
+ authorizationUrl?: string;
418
+ tokenUrl?: string;
419
+ audiences?: string[];
420
+ tokenParamName?: string;
421
+ registrationUrl?: string;
422
+ }
423
+ /**
424
+ * Auth provider type for MCP servers
425
+ */
426
+ export type McpAuthProviderType = "dynamic_discovery" | "google_credentials" | "service_account_impersonation";
427
+ /**
428
+ * CLI MCP Server configuration
429
+ *
430
+ * Supports multiple transport types:
431
+ * - stdio: command, args, env, cwd
432
+ * - SSE: url
433
+ * - Streamable HTTP: httpUrl, headers
434
+ * - WebSocket: tcp
435
+ *
436
+ * This interface aligns with MCPServerConfig in @qwen-code/qwen-code-core.
437
+ */
438
+ export interface CLIMcpServerConfig {
439
+ command?: string;
440
+ args?: string[];
441
+ env?: Record<string, string>;
442
+ cwd?: string;
443
+ url?: string;
444
+ httpUrl?: string;
445
+ headers?: Record<string, string>;
446
+ tcp?: string;
447
+ timeout?: number;
448
+ trust?: boolean;
449
+ description?: string;
450
+ includeTools?: string[];
451
+ excludeTools?: string[];
452
+ extensionName?: string;
453
+ oauth?: McpOAuthConfig;
454
+ authProviderType?: McpAuthProviderType;
455
+ /** targetAudience format: CLIENT_ID.apps.googleusercontent.com */
456
+ targetAudience?: string;
457
+ /** targetServiceAccount format: <service-account-name>@<project-num>.iam.gserviceaccount.com */
458
+ targetServiceAccount?: string;
459
+ }
460
+ /**
461
+ * Unified MCP Server configuration
462
+ *
463
+ * Supports both external MCP servers (stdio/SSE/HTTP/WebSocket) and SDK-embedded MCP servers.
464
+ *
465
+ * @example External MCP server (stdio)
466
+ * ```typescript
467
+ * mcpServers: {
468
+ * 'my-server': { command: 'node', args: ['server.js'] }
469
+ * }
470
+ * ```
471
+ *
472
+ * @example External MCP server (SSE)
473
+ * ```typescript
474
+ * mcpServers: {
475
+ * 'remote-server': { url: 'http://localhost:3000/sse' }
476
+ * }
477
+ * ```
478
+ *
479
+ * @example External MCP server (Streamable HTTP)
480
+ * ```typescript
481
+ * mcpServers: {
482
+ * 'http-server': { httpUrl: 'http://localhost:3000/mcp', headers: { 'Authorization': 'Bearer token' } }
483
+ * }
484
+ * ```
485
+ *
486
+ * @example SDK MCP server
487
+ * ```typescript
488
+ * const server = createSdkMcpServer('weather', '1.0.0', [weatherTool]);
489
+ * mcpServers: {
490
+ * 'weather': { type: 'sdk', name: 'weather', instance: server }
491
+ * }
492
+ * ```
493
+ */
494
+ export type McpServerConfig = CLIMcpServerConfig | SDKMcpServerConfig;
495
+ /**
496
+ * Type guard to check if a config is an SDK MCP server
497
+ */
498
+ export declare function isSdkMcpServerConfig(config: McpServerConfig): config is SDKMcpServerConfig;
499
+ /**
500
+ * Configuration options for creating a query session with the Qwen CLI.
501
+ */
502
+ export interface QueryOptions {
503
+ /**
504
+ * The working directory for the query session.
505
+ * This determines the context in which file operations and commands are executed.
506
+ * @default process.cwd()
507
+ */
508
+ cwd?: string;
509
+ /**
510
+ * The AI model to use for the query session.
511
+ * This takes precedence over the environment variables `OPENAI_MODEL` and `QWEN_MODEL`
512
+ * @example 'qwen-max', 'qwen-plus', 'qwen-turbo'
513
+ */
514
+ model?: string;
515
+ /**
516
+ * Path to the Qwen CLI executable or runtime specification.
517
+ *
518
+ * Supports multiple formats:
519
+ * - 'qwen' -> native binary (auto-detected from PATH)
520
+ * - '/path/to/qwen' -> native binary (explicit path)
521
+ * - '/path/to/cli.js' -> Node.js bundle (default for .js files)
522
+ * - '/path/to/index.ts' -> TypeScript source (requires tsx)
523
+ * - 'bun:/path/to/cli.js' -> Force Bun runtime
524
+ * - 'node:/path/to/cli.js' -> Force Node.js runtime
525
+ * - 'tsx:/path/to/index.ts' -> Force tsx runtime
526
+ * - 'deno:/path/to/cli.ts' -> Force Deno runtime
527
+ *
528
+ * If not provided, the SDK will auto-detect the native binary in this order:
529
+ * 1. QWEN_CODE_CLI_PATH environment variable
530
+ * 2. ~/.volta/bin/qwen
531
+ * 3. ~/.npm-global/bin/qwen
532
+ * 4. /usr/local/bin/qwen
533
+ * 5. ~/.local/bin/qwen
534
+ * 6. ~/node_modules/.bin/qwen
535
+ * 7. ~/.yarn/bin/qwen
536
+ *
537
+ * The .ts files are only supported for debugging purposes.
538
+ *
539
+ * @example 'qwen'
540
+ * @example '/usr/local/bin/qwen'
541
+ * @example 'tsx:/path/to/packages/cli/src/index.ts'
542
+ */
543
+ pathToQwenExecutable?: string;
544
+ /**
545
+ * Environment variables to pass to the Qwen CLI process.
546
+ * These variables will be merged with the current process environment.
547
+ */
548
+ env?: Record<string, string>;
549
+ /**
550
+ * Permission mode controlling how the SDK handles tool execution approval.
551
+ *
552
+ * - 'default': Write tools are denied unless approved via `canUseTool` callback or in `allowedTools`.
553
+ * Read-only tools execute without confirmation.
554
+ * - 'plan': Blocks all write tools, instructing AI to present a plan first.
555
+ * Read-only tools execute normally.
556
+ * - 'auto-edit': Auto-approve edit tools (edit, write_file) while other tools require confirmation.
557
+ * - 'yolo': All tools execute automatically without confirmation.
558
+ *
559
+ * **Priority Chain (highest to lowest):**
560
+ * 1. `excludeTools` - Blocks tools completely (returns permission error)
561
+ * 2. `permissionMode: 'plan'` - Blocks non-read-only tools (except exit_plan_mode)
562
+ * 3. `permissionMode: 'yolo'` - Auto-approves all tools
563
+ * 4. `allowedTools` - Auto-approves matching tools
564
+ * 5. `canUseTool` callback - Custom approval logic
565
+ * 6. Default behavior - Auto-deny in SDK mode
566
+ *
567
+ * @default 'default'
568
+ * @see canUseTool For custom permission handling
569
+ * @see allowedTools For auto-approving specific tools
570
+ * @see excludeTools For blocking specific tools
571
+ */
572
+ permissionMode?: "default" | "plan" | "auto-edit" | "yolo";
573
+ /**
574
+ * Custom permission handler for tool execution approval.
575
+ *
576
+ * This callback is invoked when a tool requires confirmation and allows you to
577
+ * programmatically approve or deny execution. It acts as a fallback after
578
+ * `allowedTools` check but before default denial.
579
+ *
580
+ * **When is this called?**
581
+ * - Only for tools requiring confirmation (write operations, shell commands, etc.)
582
+ * - After `excludeTools` and `allowedTools` checks
583
+ * - Not called in 'yolo' mode or 'plan' mode
584
+ * - Not called for tools already in `allowedTools`
585
+ *
586
+ * **Usage with permissionMode:**
587
+ * - 'default': Invoked for all write tools not in `allowedTools`; if not provided, auto-denied.
588
+ * - 'auto-edit': Invoked for non-edit tools (edit/write_file auto-approved); if not provided, auto-denied.
589
+ * - 'plan': Not invoked; write tools are blocked by plan mode.
590
+ * - 'yolo': Not invoked; all tools auto-approved.
591
+ *
592
+ * @see allowedTools For auto-approving tools without callback
593
+ */
594
+ canUseTool?: CanUseTool;
595
+ /**
596
+ * MCP (Model Context Protocol) servers to connect to.
597
+ *
598
+ * Supports both external MCP servers and SDK-embedded MCP servers:
599
+ *
600
+ * **External MCP servers** - Run in separate processes, connected via stdio/SSE/HTTP:
601
+ * ```typescript
602
+ * mcpServers: {
603
+ * 'stdio-server': { command: 'node', args: ['server.js'], env: { PORT: '3000' } },
604
+ * 'sse-server': { url: 'http://localhost:3000/sse' },
605
+ * 'http-server': { httpUrl: 'http://localhost:3000/mcp' }
606
+ * }
607
+ * ```
608
+ *
609
+ * **SDK MCP servers** - Run in the SDK process, connected via in-memory transport:
610
+ * ```typescript
611
+ * const myTool = tool({
612
+ * name: 'my_tool',
613
+ * description: 'My custom tool',
614
+ * inputSchema: { type: 'object', properties: { input: { type: 'string' } } },
615
+ * handler: async (input) => ({ result: input.input.toUpperCase() }),
616
+ * });
617
+ *
618
+ * const server = createSdkMcpServer('my-server', '1.0.0', [myTool]);
619
+ *
620
+ * mcpServers: {
621
+ * 'my-server': { type: 'sdk', name: 'my-server', instance: server }
622
+ * }
623
+ * ```
624
+ */
625
+ mcpServers?: Record<string, McpServerConfig>;
626
+ /**
627
+ * AbortController to cancel the query session.
628
+ * Call abortController.abort() to terminate the session and cleanup resources.
629
+ * Remember to handle the AbortError when the session is aborted.
630
+ */
631
+ abortController?: AbortController;
632
+ /**
633
+ * Enable debug mode for verbose logging.
634
+ * When true, additional diagnostic information will be output.
635
+ * Use this with `logLevel` to control the verbosity of the logs.
636
+ * @default false
637
+ */
638
+ debug?: boolean;
639
+ /**
640
+ * Custom handler for stderr output from the Qwen CLI process.
641
+ * Use this to capture and process error messages or diagnostic output.
642
+ */
643
+ stderr?: (message: string) => void;
644
+ /**
645
+ * Logging level for the SDK.
646
+ * Controls the verbosity of log messages output by the SDK.
647
+ * @default 'info'
648
+ */
649
+ logLevel?: "debug" | "info" | "warn" | "error";
650
+ /**
651
+ * Maximum number of conversation turns before the session automatically terminates.
652
+ * A turn consists of a user message and an assistant response.
653
+ * @default -1 (unlimited)
654
+ */
655
+ maxSessionTurns?: number;
656
+ /**
657
+ * Equivalent to `tool.core` in settings.json.
658
+ * List of core tools to enable for the session.
659
+ * If specified, only these tools will be available to the AI.
660
+ * @example ['read_file', 'write_file', 'run_terminal_cmd']
661
+ */
662
+ coreTools?: string[];
663
+ /**
664
+ * Equivalent to `tool.exclude` in settings.json.
665
+ * List of tools to exclude from the session.
666
+ *
667
+ * **Behavior:**
668
+ * - Excluded tools return a permission error immediately when invoked
669
+ * - Takes highest priority - overrides all other permission settings
670
+ * - Tools will not be available to the AI, even if in `coreTools` or `allowedTools`
671
+ *
672
+ * **Pattern matching:**
673
+ * - Tool name: `'write_file'`, `'run_shell_command'`
674
+ * - Tool class: `'WriteTool'`, `'ShellTool'`
675
+ * - Shell command prefix: `'ShellTool(git commit)'` (matches commands starting with "git commit")
676
+ *
677
+ * @example ['run_terminal_cmd', 'delete_file', 'ShellTool(rm )']
678
+ * @see allowedTools For allowing specific tools
679
+ */
680
+ excludeTools?: string[];
681
+ /**
682
+ * Equivalent to `tool.allowed` in settings.json.
683
+ * List of tools that are allowed to run without confirmation.
684
+ *
685
+ * **Behavior:**
686
+ * - Matching tools bypass `canUseTool` callback and execute automatically
687
+ * - Only applies when tool requires confirmation (write operations, shell commands)
688
+ * - Checked after `excludeTools` but before `canUseTool` callback
689
+ * - Does not override `permissionMode: 'plan'` (plan mode blocks all write tools)
690
+ * - Has no effect in `permissionMode: 'yolo'` (already auto-approved)
691
+ *
692
+ * **Pattern matching:**
693
+ * - Tool name: `'write_file'`, `'run_shell_command'`
694
+ * - Tool class: `'WriteTool'`, `'ShellTool'`
695
+ * - Shell command prefix: `'ShellTool(git status)'` (matches commands starting with "git status")
696
+ *
697
+ * **Use cases:**
698
+ * - Auto-approve safe shell commands: `['ShellTool(git status)', 'ShellTool(ls)']`
699
+ * - Auto-approve specific tools: `['write_file', 'edit']`
700
+ * - Combine with `permissionMode: 'default'` to selectively auto-approve tools
701
+ *
702
+ * @example ['read_file', 'ShellTool(git status)', 'ShellTool(npm test)']
703
+ * @see canUseTool For custom approval logic
704
+ * @see excludeTools For blocking specific tools
705
+ */
706
+ allowedTools?: string[];
707
+ /**
708
+ * Authentication type for the AI service.
709
+ * - 'openai': Use OpenAI-compatible authentication
710
+ * - 'qwen-oauth': Use Qwen OAuth authentication
711
+ *
712
+ * Though we support 'qwen-oauth', it's not recommended to use it in the SDK.
713
+ * Because the credentials are stored in `~/.qwen` and may need to refresh periodically.
714
+ */
715
+ authType?: "openai" | "qwen-oauth";
716
+ /**
717
+ * Configuration for subagents that can be invoked during the session.
718
+ * Subagents are specialized AI agents that can handle specific tasks or domains.
719
+ * The invocation is marked as a `task` tool use with the name of agent and a tool_use_id.
720
+ * The tool use of these agent is marked with the parent_tool_use_id of the `task` tool use.
721
+ */
722
+ agents?: SubagentConfig[];
723
+ /**
724
+ * Include partial messages in the response stream.
725
+ * When true, the SDK will emit incomplete messages as they are being generated,
726
+ * allowing for real-time streaming of the AI's response.
727
+ * @default false
728
+ */
729
+ includePartialMessages?: boolean;
730
+ /**
731
+ * Timeout configuration for various SDK operations.
732
+ * All values are in milliseconds.
733
+ */
734
+ timeout?: {
735
+ /**
736
+ * Timeout for the `canUseTool` callback.
737
+ * If the callback doesn't resolve within this time, the permission request
738
+ * will be denied with a timeout error (fail-safe behavior).
739
+ * @default 60000 (1 minute)
740
+ */
741
+ canUseTool?: number;
742
+ /**
743
+ * Timeout for SDK MCP tool calls.
744
+ * This applies to tool calls made to SDK-embedded MCP servers.
745
+ * @default 60000 (1 minute)
746
+ */
747
+ mcpRequest?: number;
748
+ /**
749
+ * Timeout for SDK→CLI control requests.
750
+ * This applies to internal control operations like initialize, interrupt,
751
+ * setPermissionMode, setModel, etc.
752
+ * @default 60000 (1 minute)
753
+ */
754
+ controlRequest?: number;
755
+ /**
756
+ * Timeout for waiting before closing CLI's stdin after user messages are sent.
757
+ * In multi-turn mode with SDK MCP servers, after all user messages are processed,
758
+ * the SDK waits for the first result message to ensure all initialization
759
+ * (control responses, MCP server setup, etc.) is complete before closing stdin.
760
+ * This timeout is a fallback to avoid hanging indefinitely.
761
+ * @default 60000 (1 minute)
762
+ */
763
+ streamClose?: number;
764
+ };
765
+ }
766
+ export declare class Query implements AsyncIterable<SDKMessage> {
767
+ private transport;
768
+ private options;
769
+ private sessionId;
770
+ private inputStream;
771
+ private sdkMessages;
772
+ private abortController;
773
+ private pendingControlRequests;
774
+ private pendingMcpResponses;
775
+ private sdkMcpTransports;
776
+ private sdkMcpServers;
777
+ readonly initialized: Promise<void>;
778
+ private closed;
779
+ private messageRouterStarted;
780
+ private firstResultReceivedPromise?;
781
+ private firstResultReceivedResolve?;
782
+ private readonly isSingleTurn;
783
+ constructor(transport: Transport, options: QueryOptions, singleTurn?: boolean);
784
+ private initializeSdkMcpServers;
785
+ /**
786
+ * Handle response messages from SDK MCP servers
787
+ *
788
+ * When an MCP server sends a response via transport.send(), this callback
789
+ * routes it back to the pending request that's waiting for it.
790
+ */
791
+ private handleMcpServerResponse;
792
+ /**
793
+ * Get SDK MCP servers config for CLI initialization
794
+ *
795
+ * Only SDK servers are sent in the initialize request.
796
+ */
797
+ private getSdkMcpServersForCli;
798
+ /**
799
+ * Get external MCP servers (non-SDK) that should be managed by the CLI
800
+ */
801
+ private getMcpServersForCli;
802
+ private initialize;
803
+ private startMessageRouter;
804
+ private routeMessage;
805
+ private handleControlRequest;
806
+ private handlePermissionRequest;
807
+ private handleMcpMessage;
808
+ private handleMcpRequest;
809
+ private handleControlResponse;
810
+ private handleControlCancelRequest;
811
+ private sendControlRequest;
812
+ private sendControlResponse;
813
+ close(): Promise<void>;
814
+ private readSdkMessages;
815
+ next(...args: [
816
+ ] | [
817
+ unknown
818
+ ]): Promise<IteratorResult<SDKMessage>>;
819
+ return(value?: unknown): Promise<IteratorResult<SDKMessage>>;
820
+ throw(e?: unknown): Promise<IteratorResult<SDKMessage>>;
821
+ [Symbol.asyncIterator](): AsyncIterator<SDKMessage>;
822
+ streamInput(messages: AsyncIterable<SDKUserMessage>): Promise<void>;
823
+ endInput(): void;
824
+ interrupt(): Promise<void>;
825
+ setPermissionMode(mode: string): Promise<void>;
826
+ setModel(model: string): Promise<void>;
827
+ /**
828
+ * Get list of control commands supported by the CLI
829
+ *
830
+ * @returns Promise resolving to list of supported command names
831
+ * @throws Error if query is closed
832
+ */
833
+ supportedCommands(): Promise<Record<string, unknown> | null>;
834
+ /**
835
+ * Get the status of MCP servers
836
+ *
837
+ * @returns Promise resolving to MCP server status information
838
+ * @throws Error if query is closed
839
+ */
840
+ mcpServerStatus(): Promise<Record<string, unknown> | null>;
841
+ getSessionId(): string;
842
+ isClosed(): boolean;
843
+ }
844
+ export declare function query({ prompt, options, }: {
845
+ /**
846
+ * The prompt to send to the Qwen Code CLI process.
847
+ * - `string` for single-turn query,
848
+ * - `AsyncIterable<SDKUserMessage>` for multi-turn query.
849
+ *
850
+ * The transport will remain open until the prompt is done.
851
+ */
852
+ prompt: string | AsyncIterable<SDKUserMessage>;
853
+ /**
854
+ * Configuration options for the query.
855
+ */
856
+ options?: QueryOptions;
857
+ }): Query;
858
+ export declare class AbortError extends Error {
859
+ constructor(message?: string);
860
+ }
861
+ export declare function isAbortError(error: unknown): error is AbortError;
862
+ export type LogLevel = "debug" | "info" | "warn" | "error";
863
+ export interface LoggerConfig {
864
+ debug?: boolean;
865
+ stderr?: (message: string) => void;
866
+ logLevel?: LogLevel;
867
+ }
868
+ export interface ScopedLogger {
869
+ debug(message: string, ...args: unknown[]): void;
870
+ info(message: string, ...args: unknown[]): void;
871
+ warn(message: string, ...args: unknown[]): void;
872
+ error(message: string, ...args: unknown[]): void;
873
+ }
874
+ export declare class SdkLogger {
875
+ private static config;
876
+ private static effectiveLevel;
877
+ static configure(config: LoggerConfig): void;
878
+ private static determineLogLevel;
879
+ private static isValidLogLevel;
880
+ private static shouldLog;
881
+ private static formatTimestamp;
882
+ private static formatMessage;
883
+ private static log;
884
+ static createLogger(scope: string): ScopedLogger;
885
+ static getEffectiveLevel(): LogLevel;
886
+ }
887
+ export type CallToolResult = z.infer<typeof CallToolResultSchema>;
888
+ /**
889
+ * SDK MCP Tool Definition with Zod schema type inference
890
+ */
891
+ export type SdkMcpToolDefinition<Schema extends ZodRawShape = ZodRawShape> = {
892
+ name: string;
893
+ description: string;
894
+ inputSchema: Schema;
895
+ handler: (args: z.infer<ZodObject<Schema, "strip", ZodTypeAny>>, extra: unknown) => Promise<CallToolResult>;
896
+ };
897
+ /**
898
+ * Create an SDK MCP tool definition with Zod schema inference
899
+ *
900
+ * @example
901
+ * ```typescript
902
+ * import { z } from 'zod';
903
+ * import { tool } from '@qwen-code/sdk';
904
+ *
905
+ * const calculatorTool = tool(
906
+ * 'calculate_sum',
907
+ * 'Calculate the sum of two numbers',
908
+ * { a: z.number(), b: z.number() },
909
+ * async (args) => {
910
+ * // args is inferred as { a: number, b: number }
911
+ * return { content: [{ type: 'text', text: String(args.a + args.b) }] };
912
+ * }
913
+ * );
914
+ * ```
915
+ */
916
+ export declare function tool<Schema extends ZodRawShape>(name: string, description: string, inputSchema: Schema, handler: (args: z.infer<ZodObject<Schema, "strip", ZodTypeAny>>, extra: unknown) => Promise<CallToolResult>): SdkMcpToolDefinition<Schema>;
917
+ /**
918
+ * Options for creating an SDK MCP server
919
+ */
920
+ export type CreateSdkMcpServerOptions = {
921
+ name: string;
922
+ version?: string;
923
+ tools?: Array<SdkMcpToolDefinition<any>>;
924
+ };
925
+ /**
926
+ * SDK MCP Server configuration with instance
927
+ */
928
+ export type McpSdkServerConfigWithInstance = {
929
+ type: "sdk";
930
+ name: string;
931
+ instance: McpServer;
932
+ };
933
+ /**
934
+ * Creates an MCP server instance that can be used with the SDK transport.
935
+ *
936
+ * @example
937
+ * ```typescript
938
+ * import { z } from 'zod';
939
+ * import { tool, createSdkMcpServer } from '@qwen-code/sdk';
940
+ *
941
+ * const calculatorTool = tool(
942
+ * 'calculate_sum',
943
+ * 'Add two numbers',
944
+ * { a: z.number(), b: z.number() },
945
+ * async (args) => ({ content: [{ type: 'text', text: String(args.a + args.b) }] })
946
+ * );
947
+ *
948
+ * const server = createSdkMcpServer({
949
+ * name: 'calculator',
950
+ * version: '1.0.0',
951
+ * tools: [calculatorTool],
952
+ * });
953
+ * ```
954
+ */
955
+ export declare function createSdkMcpServer(options: CreateSdkMcpServerOptions): McpSdkServerConfigWithInstance;
956
+
957
+ export {};