@preapexis/piexis 0.1.2 → 0.2.4

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 (154) hide show
  1. package/.github/workflows/publish.yml +35 -0
  2. package/AGENTS.md +21 -41
  3. package/README.md +75 -142
  4. package/extensions/agents.ts +205 -0
  5. package/extensions/ask-question.ts +54 -95
  6. package/extensions/recommended-tools.ts +62 -0
  7. package/extensions/ui.ts +204 -58
  8. package/lib/agent-config.ts +55 -0
  9. package/lib/agents.ts +208 -0
  10. package/lib/question-model.ts +98 -0
  11. package/lib/question-ui.ts +214 -0
  12. package/lib/recommended-tools.ts +119 -0
  13. package/lib/subagent-runner.ts +146 -0
  14. package/lib/ui-tips.json +41 -0
  15. package/package.json +9 -12
  16. package/prompts/init.md +10 -2
  17. package/prompts/summary.md +7 -6
  18. package/schemas/agent.schema.json +48 -0
  19. package/scripts/release.mjs +32 -0
  20. package/skills/{claude-api/LICENSE.txt → caveman/LICENSE} +2 -2
  21. package/skills/caveman/LICENSE-MIT +21 -0
  22. package/skills/caveman/NOTICE +10 -0
  23. package/skills/caveman/SKILL.md +89 -0
  24. package/skills/find-skills/SKILL.md +141 -0
  25. package/skills/ponytail/LICENSE +21 -0
  26. package/skills/ponytail/NOTICE +9 -0
  27. package/skills/ponytail/SKILL.md +52 -0
  28. package/skills-lock.json +6 -0
  29. package/tests/agents.test.mjs +605 -0
  30. package/tests/ask-question-pty.test.mjs +16 -0
  31. package/tests/ask-question.test.mjs +269 -0
  32. package/tests/fixtures/agents-provider.ts +55 -0
  33. package/tests/fixtures/ask-question-pty.py +91 -0
  34. package/tests/fixtures/ask-question-terminal.mjs +69 -0
  35. package/tests/fixtures/recommended-tools-terminal.mjs +103 -0
  36. package/tests/init-workflow.test.mjs +31 -0
  37. package/tests/recommended-tools-pty.test.mjs +16 -0
  38. package/tests/recommended-tools.test.mjs +423 -0
  39. package/tests/resources.test.mjs +66 -0
  40. package/tests/skills-routing.test.mjs +7 -4
  41. package/tests/ui-tip-reload.test.mjs +70 -0
  42. package/tests/ui.test.mjs +450 -0
  43. package/tsconfig.json +1 -0
  44. package/.github/workflows/npm-publish.yml +0 -63
  45. package/PERMISSION_MODES_PLAN.md +0 -279
  46. package/WHAT_YOU_GET.md +0 -153
  47. package/eval/README.md +0 -72
  48. package/eval/permission-cases.json +0 -28
  49. package/eval/permissions.mjs +0 -103
  50. package/extensions/background-tasks.ts +0 -433
  51. package/extensions/background-worker.ts +0 -50
  52. package/extensions/glob.ts +0 -32
  53. package/extensions/mode.ts +0 -397
  54. package/lib/bash-approvals.ts +0 -113
  55. package/lib/bash-policy.ts +0 -164
  56. package/lib/mode-policy.ts +0 -174
  57. package/lib/path-policy.ts +0 -182
  58. package/lib/permission-classifier.ts +0 -128
  59. package/lib/permission-config.ts +0 -91
  60. package/lib/permission-denials.ts +0 -32
  61. package/lib/permission-intent.ts +0 -128
  62. package/lib/permission-taxonomy.ts +0 -15
  63. package/lib/task-broker.ts +0 -65
  64. package/lib/task-checkout.ts +0 -39
  65. package/lib/task-git.ts +0 -44
  66. package/lib/task-patch.ts +0 -106
  67. package/lib/task-permissions.ts +0 -51
  68. package/lib/task-report.ts +0 -62
  69. package/lib/task-worktree-policy.ts +0 -56
  70. package/skills/claude-api/SKILL.md +0 -572
  71. package/skills/claude-api/csharp/claude-api/README.md +0 -362
  72. package/skills/claude-api/csharp/claude-api/batches.md +0 -14
  73. package/skills/claude-api/csharp/claude-api/files-api.md +0 -25
  74. package/skills/claude-api/csharp/claude-api/streaming.md +0 -28
  75. package/skills/claude-api/csharp/claude-api/tool-use.md +0 -164
  76. package/skills/claude-api/curl/examples.md +0 -256
  77. package/skills/claude-api/curl/managed-agents.md +0 -371
  78. package/skills/claude-api/go/claude-api/README.md +0 -188
  79. package/skills/claude-api/go/claude-api/files-api.md +0 -23
  80. package/skills/claude-api/go/claude-api/streaming.md +0 -43
  81. package/skills/claude-api/go/claude-api/tool-use.md +0 -220
  82. package/skills/claude-api/go/managed-agents/README.md +0 -564
  83. package/skills/claude-api/java/claude-api/README.md +0 -238
  84. package/skills/claude-api/java/claude-api/files-api.md +0 -27
  85. package/skills/claude-api/java/claude-api/streaming.md +0 -24
  86. package/skills/claude-api/java/claude-api/tool-use.md +0 -228
  87. package/skills/claude-api/java/managed-agents/README.md +0 -443
  88. package/skills/claude-api/php/claude-api/README.md +0 -174
  89. package/skills/claude-api/php/claude-api/batches.md +0 -15
  90. package/skills/claude-api/php/claude-api/files-api.md +0 -13
  91. package/skills/claude-api/php/claude-api/streaming.md +0 -27
  92. package/skills/claude-api/php/claude-api/tool-use.md +0 -253
  93. package/skills/claude-api/php/managed-agents/README.md +0 -443
  94. package/skills/claude-api/python/claude-api/README.md +0 -565
  95. package/skills/claude-api/python/claude-api/batches.md +0 -198
  96. package/skills/claude-api/python/claude-api/files-api.md +0 -170
  97. package/skills/claude-api/python/claude-api/sdk-upgrade.md +0 -286
  98. package/skills/claude-api/python/claude-api/streaming.md +0 -179
  99. package/skills/claude-api/python/claude-api/tool-use.md +0 -627
  100. package/skills/claude-api/python/managed-agents/README.md +0 -335
  101. package/skills/claude-api/ruby/claude-api/README.md +0 -134
  102. package/skills/claude-api/ruby/claude-api/streaming.md +0 -16
  103. package/skills/claude-api/ruby/claude-api/tool-use.md +0 -41
  104. package/skills/claude-api/ruby/managed-agents/README.md +0 -394
  105. package/skills/claude-api/shared/admin-api.md +0 -179
  106. package/skills/claude-api/shared/agent-design.md +0 -101
  107. package/skills/claude-api/shared/anthropic-cli.md +0 -269
  108. package/skills/claude-api/shared/claude-platform-on-aws.md +0 -59
  109. package/skills/claude-api/shared/cost-optimization.md +0 -233
  110. package/skills/claude-api/shared/error-codes.md +0 -262
  111. package/skills/claude-api/shared/live-sources.md +0 -166
  112. package/skills/claude-api/shared/managed-agents-api-reference.md +0 -455
  113. package/skills/claude-api/shared/managed-agents-client-patterns.md +0 -220
  114. package/skills/claude-api/shared/managed-agents-core.md +0 -359
  115. package/skills/claude-api/shared/managed-agents-environments.md +0 -226
  116. package/skills/claude-api/shared/managed-agents-events.md +0 -290
  117. package/skills/claude-api/shared/managed-agents-memory.md +0 -201
  118. package/skills/claude-api/shared/managed-agents-multiagent.md +0 -260
  119. package/skills/claude-api/shared/managed-agents-onboarding.md +0 -82
  120. package/skills/claude-api/shared/managed-agents-outcomes.md +0 -108
  121. package/skills/claude-api/shared/managed-agents-overview.md +0 -77
  122. package/skills/claude-api/shared/managed-agents-scheduled-deployments.md +0 -156
  123. package/skills/claude-api/shared/managed-agents-self-hosted-sandboxes.md +0 -282
  124. package/skills/claude-api/shared/managed-agents-tools.md +0 -504
  125. package/skills/claude-api/shared/managed-agents-webhooks.md +0 -143
  126. package/skills/claude-api/shared/model-migration.md +0 -1872
  127. package/skills/claude-api/shared/models.md +0 -142
  128. package/skills/claude-api/shared/platform-availability.md +0 -53
  129. package/skills/claude-api/shared/prompt-audit.md +0 -223
  130. package/skills/claude-api/shared/prompt-caching.md +0 -292
  131. package/skills/claude-api/shared/token-counting.md +0 -56
  132. package/skills/claude-api/shared/tool-use-concepts.md +0 -526
  133. package/skills/claude-api/typescript/claude-api/README.md +0 -405
  134. package/skills/claude-api/typescript/claude-api/batches.md +0 -106
  135. package/skills/claude-api/typescript/claude-api/files-api.md +0 -98
  136. package/skills/claude-api/typescript/claude-api/streaming.md +0 -178
  137. package/skills/claude-api/typescript/claude-api/tool-use.md +0 -586
  138. package/skills/claude-api/typescript/managed-agents/README.md +0 -359
  139. package/tests/auto-permissions.test.mjs +0 -315
  140. package/tests/background-tasks.test.mjs +0 -27
  141. package/tests/background-worker.test.mjs +0 -60
  142. package/tests/bash-permissions.test.mjs +0 -276
  143. package/tests/glob.test.mjs +0 -31
  144. package/tests/mode.test.mjs +0 -62
  145. package/tests/permission-evaluation.test.mjs +0 -70
  146. package/tests/permission-foundation.test.mjs +0 -194
  147. package/tests/permission-policy.test.mjs +0 -158
  148. package/tests/runtime/README.md +0 -51
  149. package/tests/runtime/harness.mjs +0 -190
  150. package/tests/runtime/permissions.test.mjs +0 -192
  151. package/tests/runtime/tui.test.mjs +0 -60
  152. package/tests/task-integration.test.mjs +0 -324
  153. package/tests/task-permissions.test.mjs +0 -178
  154. package/tests/task-worktree-policy.test.mjs +0 -53
@@ -1,526 +0,0 @@
1
- # Tool Use Concepts
2
-
3
- This file covers the conceptual foundations of tool use with the Claude API. For language-specific code examples, see the `python/`, `typescript/`, or other language folders. For decision heuristics on which tools to expose, how to manage context in long-running agents, and caching strategy, see `agent-design.md`.
4
-
5
- ## User-Defined Tools
6
-
7
- ### Tool Definition Structure
8
-
9
- > **Note:** When using the Tool Runner (beta), tool schemas are generated automatically from your function signatures (Python), Zod schemas (TypeScript), annotated classes (Java), `jsonschema` struct tags (Go), or `BaseTool` subclasses (Ruby). The raw JSON schema format below is for the manual approach - including PHP's `BetaRunnableTool`, which wraps a run closure around a hand-written schema - or SDKs without tool runner support.
10
-
11
- Each tool requires a name, description, and JSON Schema for its inputs:
12
-
13
- ```json
14
- {
15
- "name": "get_weather",
16
- "description": "Get current weather for a location",
17
- "input_schema": {
18
- "type": "object",
19
- "properties": {
20
- "location": {
21
- "type": "string",
22
- "description": "City and state, e.g., San Francisco, CA"
23
- },
24
- "unit": {
25
- "type": "string",
26
- "enum": ["celsius", "fahrenheit"],
27
- "description": "Temperature unit"
28
- }
29
- },
30
- "required": ["location"]
31
- }
32
- }
33
- ```
34
-
35
- **Best practices for tool definitions:**
36
-
37
- - Use clear, descriptive names (e.g., `get_weather`, `search_database`, `send_email`)
38
- - Write detailed descriptions - Claude uses these to decide when to use the tool. Be **prescriptive about *when* to call it**, not just what it does (e.g. "Call this when the user asks about current prices or recent events"). On recent Opus models, which reach for tools more conservatively, trigger conditions in the description give measurable lift in should-call rate.
39
- - Include descriptions for each property
40
- - Use `enum` for parameters with a fixed set of values
41
- - Mark truly required parameters in `required`; make others optional with defaults
42
-
43
- ---
44
-
45
- ### Tool Choice Options
46
-
47
- Control when Claude uses tools:
48
-
49
- | Value | Behavior |
50
- | --------------------------------- | --------------------------------------------- |
51
- | `{"type": "auto"}` | Claude decides whether to use tools (default) |
52
- | `{"type": "any"}` | Claude must use at least one tool |
53
- | `{"type": "tool", "name": "..."}` | Claude must use the specified tool |
54
- | `{"type": "none"}` | Claude cannot use tools |
55
-
56
- Any `tool_choice` value can also include `"disable_parallel_tool_use": true` to force Claude to use at most one tool per response. By default, Claude may request multiple tool calls in a single response.
57
-
58
- **Claude Fable 5.1, Claude Mythos 5.1, and Mythos Preview reject forced tool use:** `{"type": "any"}` and `{"type": "tool", "name": ...}` return a 400 there (`tool_choice: type "tool" and "any" are not supported for this model.` - on `count_tokens` and Batches too). It is a model-specific restriction (Claude Fable 5 and Claude Opus 5 accept them). Use `{"type": "auto"}` and state the expectation in the prompt ("Use the get_weather tool to answer") - `strict: true` on the tool keeps the schema-valid-arguments guarantee `any` gave you - or structured outputs (`output_config.format`) when the forced call only existed to extract JSON. `auto` and `none` are unaffected; `disable_parallel_tool_use` with `auto` still means at most one call (the "exactly one" combination with `any`/`tool` is gone). Combining `tool_choice` `any` with `strict: true` applies only on models that support forced tool use. See `shared/model-migration.md` -> Migrating to Claude Fable 5.1 from Claude Fable 5.
59
-
60
- ---
61
-
62
- ### Tool Runner vs Manual Loop
63
-
64
- **Tool Runner (Recommended):** The SDK's tool runner handles the agentic loop automatically - it calls the API, detects tool use requests, executes your tool functions, feeds results back to Claude, and repeats until Claude stops calling tools. Available in Python, TypeScript, Java, Go, Ruby, PHP, and C# SDKs (beta). The Python SDK also provides MCP conversion helpers (`anthropic.lib.tools.mcp`) to convert MCP tools, prompts, and resources for use with the tool runner - see `python/claude-api/tool-use.md` for details. **Default to the tool runner** for any custom-tool agent.
65
-
66
- **The tool runner is not a black box - "I need control" is rarely a reason to drop to the manual loop.** Each iteration yields the assistant message *before* the tools run and lets you intervene, so most "fine-grained control" needs are covered without hand-writing the loop:
67
-
68
- - **Human-in-the-loop approval / gating** - gate in the tool's run function (return a "user declined" result instead of executing), or inspect the tool call in the yielded message and override the pending request with `set_messages_params()` / `setMessagesParams()` / `append_messages()` / `pushMessages()` to allow or deny *before* the tool executes. The runner runs your function automatically only if you don't intervene.
69
- - **Error interception** - inspect the tool result before it returns to Claude (`generate_tool_call_response()` / `generateToolResponse()`); stop early or handle it yourself.
70
- - **Result modification** - mutate the tool result before it goes back (e.g. add `cache_control` for prompt caching, or transform the output).
71
- - **Per-turn retries / param changes** - e.g. bump `max_tokens` and re-run a truncated turn; bound the whole loop with `max_iterations`.
72
- - **Streaming and automatic compaction** are both supported.
73
-
74
- These hooks are SDK helper features, not separate API parameters - for the exact method names and worked examples, WebFetch the per-language SDK repo listed in `shared/live-sources.md` -> *Claude API SDK Repositories* (the tool-runner helpers live in each repo's `tools.md` / `helpers.md`). The bundled `python/claude-api/tool-use.md` and `typescript/claude-api/tool-use.md` show the basic tool-runner setup.
75
-
76
- **Don't drop to a manual loop because of these misconceptions:**
77
-
78
- - The tool runner does not require Zod/Pydantic - `betaTool()` (TS) and `@beta_tool` (Python) accept raw JSON Schema; other SDKs use plain structs/maps/classes.
79
- - The runner makes detecting the final turn *easier*, not harder - iteration ends when Claude stops calling tools, and the last yielded message is the final response. Most SDKs also offer a one-shot variant (`runner.until_done()` / `runner.runUntilDone()` / `RunToCompletion()`).
80
- - Confirmation/approval gates work with the runner (see Security below).
81
-
82
- **Manual Agentic Loop:** Reach for this only when you want to own the *entire* loop - you need control the runner does not expose (e.g., a custom transport, request shapes the SDK cannot build, per-token streaming on SDKs whose runner does not support it), you'd rather not take the beta dependency, or your control flow doesn't fit the runner's per-turn hooks (e.g. interleaving unrelated work mid-loop). Approval gates, logging, interception, result modification, and conditional execution do **not** require it - the tool runner covers those (above). Loop until `stop_reason == "end_turn"`, always append the full `response.content` to preserve tool_use blocks, and ensure each `tool_result` includes the matching `tool_use_id`.
83
-
84
- **Stop reasons for server-side tools:** When using server-side tools (code execution, web search, etc.), the API runs a server-side sampling loop. If this loop reaches its default limit of 10 iterations, the response will have `stop_reason: "pause_turn"`. To continue, re-send the user message and assistant response and make another API request - the server will resume where it left off. Do NOT add an extra user message like "Continue." - the API detects the trailing `server_tool_use` block and knows to resume automatically.
85
-
86
- ```python
87
- # Handle pause_turn in your agentic loop
88
- if response.stop_reason == "pause_turn":
89
- messages = [
90
- {"role": "user", "content": user_query},
91
- {"role": "assistant", "content": response.content},
92
- ]
93
- # Make another API request - server resumes automatically
94
- response = client.messages.create(
95
- model="claude-opus-5", messages=messages, tools=tools
96
- )
97
- ```
98
-
99
- **Note:** the SDK tool runners do not auto-resume `pause_turn` (as of `@anthropic-ai/sdk` 0.110.0 / `anthropic` 0.116.0) - a paused turn ends the runner and is returned as the final message, with no error. In TypeScript you can resume inside the iteration body (push the paused assistant turn back onto the runner); in Python the runner cannot be resumed mid-loop - restart a new runner with the paused turn appended, or handle `pause_turn` in a manual loop. See each language's `tool-use.md` for the pattern.
100
-
101
- Set a `max_continuations` limit (e.g., 5) to prevent infinite loops. For the full guide, see: `https://platform.claude.com/docs/en/build-with-claude/handling-stop-reasons`
102
-
103
- > **Security:** The tool runner executes your tool functions automatically whenever Claude requests them. For tools with side effects (sending emails, modifying databases, financial transactions), validate inputs and gate destructive operations behind human approval. **Both** the tool runner and the manual loop support this - with the tool runner, gate inside the tool's run function (prompt the user and return a "user declined" result instead of executing), or inspect the tool call in each yielded message and take over message history with `set_messages_params()` / `setMessagesParams()` to allow or deny *before* the tool runs (it executes your function automatically only if you don't intervene); with the manual loop you gate inline before calling the function.
104
-
105
- ---
106
-
107
- ### Handling Tool Results
108
-
109
- When Claude uses a tool, the response contains a `tool_use` block. You must:
110
-
111
- 1. Execute the tool with the provided input
112
- 2. Send the result back in a `tool_result` message
113
- 3. Continue the conversation
114
-
115
- **Error handling in tool results:** When a tool execution fails, set `"is_error": true` and provide an informative error message. Claude will typically acknowledge the error and either try a different approach or ask for clarification.
116
-
117
- **Multiple tool calls:** Claude can request multiple tools in a single response. Handle them all before continuing - send all results back in a single `user` message.
118
-
119
- ---
120
-
121
- ## Server-Side Tools: Code Execution
122
-
123
- The code execution tool lets Claude run code in a secure, sandboxed container. Unlike user-defined tools, server-side tools run on Anthropic's infrastructure - you don't execute anything client-side. Just include the tool definition and Claude handles the rest.
124
-
125
- ### Key Facts
126
-
127
- - Runs in an isolated container (1 CPU, 5 GiB RAM, 5 GiB disk)
128
- - No internet access (fully sandboxed)
129
- - Python 3.11 with data science libraries pre-installed
130
- - Containers persist for 30 days and can be reused across requests
131
- - Free when used with web search/web fetch tools; otherwise $0.05/hour after 1,550 free hours/month per organization
132
-
133
- ### Tool Definition
134
-
135
- The tool requires no schema - just declare it in the `tools` array:
136
-
137
- ```json
138
- {
139
- "type": "code_execution_20260120",
140
- "name": "code_execution"
141
- }
142
- ```
143
-
144
- Claude automatically gains access to `bash_code_execution` (run shell commands) and `text_editor_code_execution` (create/view/edit files).
145
-
146
- ### Pre-installed Python Libraries
147
-
148
- - **Data science**: pandas, numpy, scipy, scikit-learn, statsmodels
149
- - **Visualization**: matplotlib, seaborn
150
- - **File processing**: openpyxl, xlsxwriter, pillow, pypdf, pdfplumber, python-docx, python-pptx
151
- - **Math**: sympy, mpmath
152
- - **Utilities**: tqdm, python-dateutil, pytz, sqlite3
153
-
154
- Additional packages can be installed at runtime via `pip install`.
155
-
156
- ### Supported File Types for Upload
157
-
158
- | Type | Extensions |
159
- | ------ | ---------------------------------- |
160
- | Data | CSV, Excel (.xlsx/.xls), JSON, XML |
161
- | Images | JPEG, PNG, GIF, WebP |
162
- | Text | .txt, .md, .py, .js, etc. |
163
-
164
- ### Container Reuse
165
-
166
- Reuse containers across requests to maintain state (files, installed packages, variables). Extract the `container_id` from the first response and pass it to subsequent requests.
167
-
168
- ### Response Structure
169
-
170
- The response contains interleaved text and tool result blocks:
171
-
172
- - `text` - Claude's explanation
173
- - `server_tool_use` - What Claude is doing
174
- - `bash_code_execution_tool_result` - Code execution output (check `return_code` for success/failure)
175
- - `text_editor_code_execution_tool_result` - File operation results
176
-
177
- > **Security:** Always sanitize filenames with `os.path.basename()` / `path.basename()` before writing downloaded files to disk to prevent path traversal attacks. Write files to a dedicated output directory.
178
-
179
- ---
180
-
181
- ## Server-Side Tools: Web Search and Web Fetch
182
-
183
- Web search and web fetch let Claude search the web and retrieve page content. They run server-side - just include the tool definitions and Claude handles queries, fetching, and result processing automatically.
184
-
185
- ### Tool Definitions
186
-
187
- ```json
188
- [
189
- { "type": "web_search_20260209", "name": "web_search" },
190
- { "type": "web_fetch_20260209", "name": "web_fetch" }
191
- ]
192
- ```
193
-
194
- ### Dynamic Filtering (Claude Opus 5 / Fable 5 / Opus 4.8 / Opus 4.7 / Opus 4.6 / Sonnet 5 / Sonnet 4.6)
195
-
196
- The `web_search_20260209` and `web_fetch_20260209` versions support **dynamic filtering** - Claude writes and executes code to filter search results before they reach the context window, improving accuracy and token efficiency. Dynamic filtering is built into these tool versions and activates automatically; you do not need to separately declare the `code_execution` tool or pass any beta header.
197
-
198
- ```json
199
- {
200
- "tools": [
201
- { "type": "web_search_20260209", "name": "web_search" },
202
- { "type": "web_fetch_20260209", "name": "web_fetch" }
203
- ]
204
- }
205
- ```
206
-
207
- Without dynamic filtering, the previous `web_search_20250305` version is also available.
208
-
209
- > **Note:** Only include the standalone `code_execution` tool when your application needs code execution for its own purposes (data analysis, file processing, visualization) independent of web search. Including it alongside `_20260209` web tools creates a second execution environment that can confuse the model.
210
-
211
- ---
212
-
213
- ## Server-Side Tools: Programmatic Tool Calling
214
-
215
- With standard tool use, each tool call is a round trip: Claude calls, the result enters Claude's context, Claude reasons, then calls the next tool. Chained calls accumulate latency and tokens - most of that intermediate data is never needed again.
216
-
217
- Programmatic tool calling lets Claude compose those calls into a script. The script runs in the code execution container; when it invokes a tool, the container pauses, the call executes, and the result returns to the running code (not to Claude's context). The script processes it with normal control flow. Only the final output returns to Claude. Use it when chaining many tool calls or when intermediate results are large and should be filtered before reaching the context window.
218
-
219
- For full documentation, use WebFetch:
220
-
221
- - URL: `https://platform.claude.com/docs/en/agents-and-tools/tool-use/programmatic-tool-calling`
222
-
223
- ---
224
-
225
- ## Server-Side Tools: Tool Search
226
-
227
- The tool search tool lets Claude dynamically discover tools from large libraries without loading all definitions into the context window. Use it when you have many tools but only a few are relevant to any given request. Discovered tool schemas are appended to the request, not swapped in - this preserves the prompt cache (see `agent-design.md` §Caching for Agents).
228
-
229
- For full documentation, use WebFetch:
230
-
231
- - URL: `https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool`
232
-
233
- ---
234
-
235
- ## Mid-conversation tool changes (Beta)
236
-
237
- **Beta header `mid-conversation-tool-changes-2026-07-01`; Claude Opus 5 onward.** Normally `tools` is fixed for a conversation's lifetime - editing it changes the very front of the prompt prefix and invalidates the entire cache (see `prompt-caching.md` § Invalidation hierarchy). This feature lets you add and remove tools between turns while the cached prefix survives.
238
-
239
- Both operations are content blocks on a `{"role": "system", ...}` message appended to `messages[]`, and both reference a tool by name via a `tool_reference`:
240
-
241
- ```python
242
- # Removal - must sit immediately before an assistant message, or last in messages.
243
- {"role": "system", "content": [
244
- {"type": "tool_removal", "tool": {"type": "tool_reference", "name": "get_weather"}},
245
- ]}
246
-
247
- # Addition - surfaces a tool declared up front with defer_loading.
248
- {"role": "system", "content": [
249
- {"type": "tool_addition", "tool": {"type": "tool_reference", "name": "get_forecast"}},
250
- ]}
251
- ```
252
-
253
- **A tool you plan to add must already be declared in `tools[]` with `"defer_loading": True`.** Deferred tools are known to the request but not loaded into the model's context until a `tool_addition` surfaces them:
254
-
255
- ```python
256
- tools = [
257
- {"name": "get_weather", "description": "Get weather",
258
- "input_schema": {"type": "object", "properties": {"city": {"type": "string"}}}},
259
- {"name": "get_forecast", "description": "Get 5-day forecast",
260
- "input_schema": {"type": "object", "properties": {"city": {"type": "string"}}},
261
- "defer_loading": True},
262
- ]
263
- ```
264
-
265
- **To change a tool's definition**, do it across two requests: send a `tool_removal` for the old definition on the first, then carry the conversation forward with the updated entry in `tools[]` on the next.
266
-
267
- > Warning: Earlier previews used a different beta header and different block shapes; both are deprecated. Use `mid-conversation-tool-changes-2026-07-01` with `tool_addition` / `tool_removal` / `tool_reference`.
268
-
269
- SDK typings lag these blocks - pass them as plain dicts in Python, or add a `@ts-expect-error` in TypeScript.
270
-
271
- **Choosing between this and tool search:** tool search is for *discovery* - Claude finds what it needs from a large library on its own. Mid-conversation tool changes are for *control* - your application decides the tool set has changed (a mode switch, a resource that became available, a capability you want to revoke) and says so explicitly.
272
-
273
- ---
274
-
275
- ## Agent Skills (Messages API)
276
-
277
- Agent Skills package task-specific instructions and files that Claude loads when relevant (e.g., the Anthropic pre-built `pptx`, `xlsx`, `pdf`, `docx` skills). On the **Messages API**, skills are enabled via the `container` parameter alongside the code-execution tool - this is **not** the Managed Agents surface and does **not** use `client.beta.agents` / `sessions` / `environments`. Availability: see `shared/platform-availability.md`.
278
-
279
- Required on each request:
280
-
281
- 1. `client.beta.messages.create(...)` with the `code-execution-2025-08-25` beta flag (Skills is out of beta - no `skills-2025-10-02` header needed).
282
- 2. `container={"skills": [{"type": "anthropic", "skill_id": "<id>", "version": "latest"}]}` - the skills list selects which skills are available inside the execution container.
283
- 3. `tools=[{"type": "code_execution_20260521", "name": "code_execution"}]` - skills execute via code execution in the container.
284
-
285
- ```python
286
- response = client.beta.messages.create(
287
- model="claude-opus-5", max_tokens=16000,
288
- betas=["code-execution-2025-08-25"],
289
- container={"skills": [{"type": "anthropic", "skill_id": "pptx", "version": "latest"}]},
290
- tools=[{"type": "code_execution_20260521", "name": "code_execution"}],
291
- messages=[{"role": "user", "content": "Create a 3-slide presentation on X"}],
292
- )
293
- ```
294
-
295
- Generated files (`.pptx`, `.xlsx`, ...) are written inside the container; the response carries a file ID for each. Download by passing that ID to the Files API (`client.files.download(file_id)` / `GET /v1/files/{id}/content`).
296
-
297
- List available skills via `GET /v1/skills` (no beta header).
298
-
299
- ---
300
-
301
- ## MCP Connector (Beta)
302
-
303
- The MCP connector lets Claude call tools hosted on a remote MCP server directly from the Messages API - Anthropic makes the MCP connection server-side. Requires beta flag `mcp-client-2025-11-20` on `client.beta.messages.create(...)`. Availability: see `shared/platform-availability.md`.
304
-
305
- **Two parameters are required together:**
306
-
307
- - `mcp_servers` - array of server connection definitions: `[{"type": "url", "url": "<server URL>", "name": "<server-name>", "authorization_token": "<optional>"}]`
308
- - `tools` - must include an `mcp_toolset` entry that references the server by name: `[{"type": "mcp_toolset", "mcp_server_name": "<server-name>"}]`
309
-
310
- The `mcp_server_name` in the toolset must match a `name` in `mcp_servers`. Omitting the `mcp_toolset` entry is rejected as a validation error - every server in `mcp_servers` must be referenced by exactly one toolset.
311
-
312
- ```python
313
- client.beta.messages.create(
314
- model="claude-opus-5", max_tokens=1024,
315
- betas=["mcp-client-2025-11-20"],
316
- mcp_servers=[{"type": "url", "url": "https://example/sse", "name": "example-mcp"}],
317
- tools=[{"type": "mcp_toolset", "mcp_server_name": "example-mcp"}],
318
- messages=[...],
319
- )
320
- ```
321
-
322
- Go uses the typed constant `anthropic.AnthropicBetaMCPClient2025_11_20`; the older `...2025_04_04` constant is deprecated.
323
-
324
- Optional toolset fields: `default_config` (defaults for all tools, e.g. `{"enabled": false}` for allowlist mode) and `configs` (per-tool overrides keyed by tool name).
325
-
326
- ---
327
-
328
- ## Tool Use Examples
329
-
330
- You can provide sample tool calls directly in your tool definitions to demonstrate usage patterns and reduce parameter errors. This helps Claude understand how to correctly format tool inputs, especially for tools with complex schemas.
331
-
332
- For full documentation, use WebFetch:
333
-
334
- - URL: `https://platform.claude.com/docs/en/agents-and-tools/tool-use/implement-tool-use`
335
-
336
- ---
337
-
338
- ## Client-Side Tools: Computer Use
339
-
340
- Computer use lets Claude interact with a desktop environment (screenshots, mouse, keyboard). It is a client-side tool - your application provides the environment and executes the actions Claude requests; Anthropic processes the screenshots and action requests in real time but does not host the environment or retain the data.
341
-
342
- For full documentation, use WebFetch:
343
-
344
- - URL: `https://platform.claude.com/docs/en/agents-and-tools/computer-use/overview`
345
-
346
- ---
347
-
348
- ## Context Editing
349
-
350
- Context editing clears stale tool results and thinking blocks from the transcript as a long-running agent accumulates turns. Unlike compaction (which summarizes), context editing prunes - the cleared content is removed, not replaced. Use it when old tool outputs are no longer relevant and you want to keep the transcript lean without losing the conversation structure.
351
-
352
- **Beta.** Use `client.beta.messages.*` with beta `context-management-2025-06-27`. Configure via `context_management.edits` with a strategy type of `clear_tool_uses_20250919` (clear old tool results; optional `clear_tool_inputs: true` also clears the tool_use params) or `clear_thinking_20251015` (clear thinking blocks). These are **not** the compaction types - `compact_20260112` with beta `compact-2026-01-12` is the separate compaction feature.
353
-
354
- For full documentation, use WebFetch:
355
-
356
- - URL: `https://platform.claude.com/docs/en/build-with-claude/context-editing`
357
-
358
- ---
359
-
360
- ## Server-Side Tools: Advisor (Beta)
361
-
362
- The advisor tool pairs a faster, lower-cost **executor** model (the top-level `model` on the request) with a higher-intelligence **advisor** model (the `model` field inside the tool definition) that provides strategic guidance mid-generation. The executor does most of the token generation; the advisor is consulted for planning. Availability: see `shared/platform-availability.md`.
363
-
364
- ### Tool Definition
365
-
366
- ```json
367
- {
368
- "type": "advisor_20260301",
369
- "name": "advisor",
370
- "model": "claude-opus-4-8"
371
- }
372
- ```
373
-
374
- Optional fields on the tool definition:
375
-
376
- - `max_uses` - cap on advisor consultations per request. Exceeding it makes the `advisor_tool_result` block's `content` the error object `{"type": "advisor_tool_result_error", "error_code": "max_uses_exceeded"}` - the third member of the content union in the payload-shape table below.
377
- - `max_tokens` - bounds the advisor's total output (thinking + text) per call. At the cap the result block carries `stop_reason: "max_tokens"` and a truncation note is appended to the advice the executor sees; the server also emits a remaining-tokens budget block in the advisor's prompt so it self-shapes toward the cap.
378
- - `caching` - cache-control for the advisor's own prompt, same shape as a cache breakpoint: `"caching": {"type": "ephemeral", "ttl": "5m"}` (`ttl` is `"5m"` or `"1h"`, default `"5m"`). Each call writes a cache entry at that TTL so later calls in the conversation read the stable prefix. Omitted = advisor prompt not cached.
379
-
380
- **The advisor model must be at least as capable as the executor.** An invalid pairing returns `400 invalid_request_error`. Valid pairs:
381
-
382
- | Executor (request `model`) | Valid advisor (tool `model`) |
383
- |---|---|
384
- | `claude-haiku-4-5` / `claude-sonnet-4-6` / `claude-sonnet-5` / `claude-opus-4-6` / `claude-opus-4-7` | `claude-opus-5`, `claude-fable-5-1`, `claude-mythos-5-1`, `claude-fable-5`, `claude-mythos-5`, `claude-opus-4-8`, or `claude-opus-4-7` |
385
- | `claude-opus-4-8` | `claude-opus-5`, `claude-fable-5-1`, `claude-mythos-5-1`, `claude-fable-5`, `claude-mythos-5`, or `claude-opus-4-8` |
386
- | `claude-opus-5` | `claude-opus-5`, `claude-fable-5-1`, `claude-mythos-5-1`, `claude-fable-5`, or `claude-mythos-5` |
387
- | `claude-fable-5` | `claude-fable-5-1`, `claude-mythos-5-1`, `claude-fable-5`, `claude-mythos-5`, or `claude-opus-5` |
388
- | `claude-mythos-5` | `claude-mythos-5-1`, `claude-fable-5-1`, `claude-mythos-5`, `claude-fable-5`, or `claude-opus-5` |
389
- | `claude-fable-5-1` / `claude-mythos-5-1` | `claude-mythos-5-1`, `claude-fable-5-1`, `claude-mythos-5`, `claude-fable-5`, or `claude-opus-5` - and these executors reject forced `tool_choice`, so nudge the advisor call from the prompt (the `-5-1` advisors return the encrypted `advisor_redacted_result`, like claude-opus-5 / claude-fable-5 / claude-mythos-5) |
390
-
391
- > Warning: **The advisor's payload shape differs by advisor model.** The response block is always `advisor_tool_result`; what varies is its **`content`**, a discriminated union:
392
- >
393
- > | `content` type | Fields | When |
394
- > |---|---|---|
395
- > | `advisor_result` | `text`, `stop_reason` | Advisor returns plaintext (e.g. Opus 4.8) |
396
- > | `advisor_redacted_result` | `encrypted_content`, `stop_reason` | Advisor returns encrypted output - Claude Opus 5, Claude Fable 5.1, Claude Mythos 5.1, Claude Fable 5, Claude Mythos 5 |
397
- > | `advisor_tool_result_error` | `error_code` | Consultation failed - `max_uses_exceeded`, `prompt_too_long`, `too_many_requests`, `overloaded`, `unavailable`, `execution_time_exceeded`, or `model_not_found` |
398
- >
399
- > So switch on `advisor_tool_result.content` type, not on the block type. Code that reads `.text` unconditionally gets nothing back from an Claude Opus 5 advisor, because the payload is under `encrypted_content` instead - and you cannot read it, only replay it.
400
-
401
- Call via `client.beta.messages.create(...)` with `betas=["advisor-tool-2026-03-01"]` (or the `anthropic-beta: advisor-tool-2026-03-01` header). In multi-turn conversations, append the full `response.content` - including any `advisor_tool_result` blocks - back to `messages` on the next turn. If you remove the advisor tool from `tools` on a later turn while the history still contains `advisor_tool_result` blocks, the API returns a 400.
402
-
403
- > **Advisor on Managed Agents:** CMA sessions support an advisor too, configured as a `{"type": "advisor", "model"}` entry in the agent's multiagent roster rather than as a tool definition - no `max_uses`/`max_tokens`/`caching` options, and advice is delivered as thread events on the session's event stream rather than `advisor_tool_result` blocks. See `shared/managed-agents-multiagent.md` -> Advisor.
404
-
405
- ---
406
-
407
- ## Client-Side Tools: Memory
408
-
409
- The memory tool enables Claude to store and retrieve information across conversations through a memory file directory. Claude can create, read, update, and delete files that persist between sessions.
410
-
411
- ### Key Facts
412
-
413
- - Client-side tool - you control storage via your implementation
414
- - Supports commands: `view`, `create`, `str_replace`, `insert`, `delete`, `rename`
415
- - Operates on files in a `/memories` directory
416
- - The Python, TypeScript, and Java SDKs provide helper classes/functions for implementing the memory backend
417
-
418
- > **Security:** Never store API keys, passwords, tokens, or other secrets in memory files. Be cautious with personally identifiable information (PII) - check data privacy regulations (GDPR, CCPA) before persisting user data. The reference implementations have no built-in access control; in multi-user systems, implement per-user memory directories and authentication in your tool handlers.
419
-
420
- For full implementation examples, use WebFetch:
421
-
422
- - Docs: `https://platform.claude.com/docs/en/agents-and-tools/tool-use/memory-tool.md`
423
-
424
- ---
425
-
426
- ## Client-Side Tools: Bash and Text Editor
427
-
428
- The bash and text editor tools are **Anthropic-defined, schema-less** tools. Declare them by `type` and `name` only - the input schema is built into the model and cannot be modified. **Do not pass an `input_schema`**, and do not define a custom tool that happens to be named `"bash"` - that creates a user-defined tool without the built-in behavior.
429
-
430
- Both are **client-executed**: Claude returns a `tool_use` block, your code performs the action locally, and you send back a `tool_result`. The API is stateless; your application maintains the shell session or filesystem between turns.
431
-
432
- ### Bash tool declaration
433
-
434
- ```json
435
- {"type": "bash_20250124", "name": "bash"}
436
- ```
437
-
438
- | Language | Declaration |
439
- |---|---|
440
- | Python / TypeScript / Ruby / cURL | plain object `{"type": "bash_20250124", "name": "bash"}` |
441
- | Go | `anthropic.ToolUnionParam{OfBashTool20250124: &anthropic.ToolBash20250124Param{}}` |
442
- | Java | `.addTool(ToolBash20250124.builder().build())` from `com.anthropic.models.messages` |
443
- | C# | `Tools = [new ToolBash20250124()]` from `Anthropic.Models.Messages` |
444
- | PHP | `tools: [new \Anthropic\Messages\ToolBash20250124()]` |
445
-
446
- Claude's `tool_use.input` contains either `{"command": "<string>"}` or `{"restart": true}`. Check for `restart` first (reset the session, return a confirmation string); otherwise run `command` and return combined stdout + stderr.
447
-
448
- > **Security - commands are untrusted model output.** Run in an isolated environment (container, VM, or restricted user); apply an **allowlist** of permitted executables and reject shell operators (`&&`, `|`, `;`, `` ` ``, `$()`); set timeouts and resource limits; log every command. A blocklist is not sufficient.
449
-
450
- ### Text editor tool declaration
451
-
452
- ```json
453
- {"type": "text_editor_20250728", "name": "str_replace_based_edit_tool"}
454
- ```
455
-
456
- Optional field: `max_characters` to cap `view` output. Java exposes a typed `ToolTextEditor20250728` builder (`com.anthropic.models.messages`); other statically-typed SDKs follow the same naming pattern - see the Anthropic-Defined Tools section in `{lang}/claude-api/tool-use.md` for the exact class.
457
-
458
- > **Security - `path` is untrusted model output. Confine every file operation to a fixed project root.** Before executing any command, resolve the model-supplied `path` to its canonical form and verify it remains within your project root; reject the request if it escapes (`..`, symlinks, absolute paths outside the root, URL-encoded traversal like `%2e%2e%2f`). Use your language's built-in path utilities (e.g., Python `pathlib.Path.resolve()` then check `.is_relative_to(root)`). Never call `open()` / `writeFile` / `unlink` directly on the raw `path` value.
459
-
460
- `tool_use.input.command` is one of:
461
-
462
- | `command` | Other inputs | Action |
463
- |---|---|---|
464
- | `view` | `path`, optional `view_range` | Return file contents or directory listing |
465
- | `create` | `path`, `file_text` | Create/overwrite file with `file_text`. Create a backup if the file already exists. |
466
- | `str_replace` | `path`, `old_str`, `new_str` | Replace exactly one occurrence; error if 0 or >1 matches |
467
- | `insert` | `path`, `insert_line`, `insert_text` | Insert `insert_text` after line `insert_line` (0 = beginning of file) |
468
-
469
- For both tools, on error return `{"type": "tool_result", "tool_use_id": "...", "content": "<error text>", "is_error": true}` so Claude can recover.
470
-
471
- ---
472
-
473
- ## Structured Outputs
474
-
475
- Structured outputs constrain Claude's responses to follow a specific JSON schema, guaranteeing valid, parseable output. This is not a separate tool - it enhances the Messages API response format and/or tool parameter validation.
476
-
477
- Two features are available:
478
-
479
- - **JSON outputs** (`output_config.format`): Control Claude's response format
480
- - **Strict tool use** (`strict: true`): Guarantee valid tool parameter schemas
481
-
482
- **Supported models:** Claude Fable 5, Claude Mythos 5, Claude Fable 5.1, Claude Mythos 5.1, Claude Opus 5, Claude Opus 4.8, Claude Sonnet 5, and Claude Haiku 4.5. Legacy models (Claude Opus 4.5, Claude Opus 4.1) also support structured outputs.
483
-
484
- > **Recommended:** Use `client.messages.parse()` which automatically validates responses against your schema. When using `messages.create()` directly, use `output_config: {format: {...}}`. The `output_format` convenience parameter is also accepted by some SDK methods (e.g., `.parse()`), but `output_config.format` is the canonical API-level parameter.
485
-
486
- ### JSON Schema Limitations
487
-
488
- **Supported:**
489
-
490
- - Basic types: object, array, string, integer, number, boolean, null
491
- - `enum`, `const`, `anyOf`, `allOf`, `$ref`/`$def`
492
- - String formats: `date-time`, `time`, `date`, `duration`, `email`, `hostname`, `uri`, `ipv4`, `ipv6`, `uuid`
493
- - `additionalProperties: false` (required for all objects)
494
-
495
- **Not supported:**
496
-
497
- - Recursive schemas
498
- - Numerical constraints (`minimum`, `maximum`, `multipleOf`)
499
- - String constraints (`minLength`, `maxLength`)
500
- - Complex array constraints
501
- - `additionalProperties` set to anything other than `false`
502
-
503
- The Python and TypeScript SDKs automatically handle unsupported constraints by removing them from the schema sent to the API and validating them client-side.
504
-
505
- ### Important Notes
506
-
507
- - **First request latency**: New schemas incur a one-time compilation cost. Subsequent requests with the same schema use a 24-hour cache.
508
- - **Refusals**: If Claude refuses for safety reasons (`stop_reason: "refusal"`), the output may not match your schema.
509
- - **Token limits**: If `stop_reason: "max_tokens"`, output may be incomplete. Increase `max_tokens`.
510
- - **Incompatible with**: Citations (returns 400 error), message prefilling.
511
- - **Works with**: Batches API, streaming, token counting, extended thinking.
512
-
513
- ---
514
-
515
- ## Tips for Effective Tool Use
516
-
517
- 1. **Provide detailed descriptions**: Claude relies heavily on descriptions to understand when and how to use tools
518
- 2. **Use specific tool names**: `get_current_weather` is better than `weather`
519
- 3. **Validate inputs**: Always validate tool inputs before execution
520
- 4. **Handle errors gracefully**: Return informative error messages so Claude can adapt
521
- 5. **Limit tool count**: Too many tools can confuse the model - keep the set focused
522
- 6. **Test tool interactions**: Verify Claude uses tools correctly in various scenarios
523
-
524
- For detailed tool use documentation, use WebFetch:
525
-
526
- - URL: `https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview`