Skip to content

Commit 677801b

Browse files
committed
refactor: reorganize examples for better clarity
- Simplify quick_start.py to just basic examples (~45 lines) - Move tools example to dedicated using_tools.py file - Move MCP configuration examples to mcp_servers.py file - Each example file now focuses on one concept This makes the quick start truly quick and provides dedicated files for users who need specific advanced features.
1 parent b123767 commit 677801b

File tree

3 files changed

+210
-54
lines changed

3 files changed

+210
-54
lines changed

examples/mcp_servers.py

Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
#!/usr/bin/env python3
2+
"""Example demonstrating MCP (Model Context Protocol) server configuration."""
3+
4+
import anyio
5+
6+
from claude_code_sdk import (
7+
AssistantMessage,
8+
ClaudeCodeOptions,
9+
ResultMessage,
10+
SystemMessage,
11+
TextBlock,
12+
query,
13+
)
14+
15+
16+
async def basic_mcp_server_example():
17+
"""Example with basic MCP server configuration."""
18+
print("=== Basic MCP Server Example ===")
19+
20+
options = ClaudeCodeOptions(
21+
mcp_servers={
22+
"memory-server": {
23+
"command": "npx",
24+
"args": ["@modelcontextprotocol/server-memory"],
25+
}
26+
}
27+
)
28+
29+
async for message in query(
30+
prompt="What MCP tools are available from the memory server?",
31+
options=options,
32+
):
33+
if isinstance(message, SystemMessage) and message.subtype == "init":
34+
if "mcp_servers" in message.data:
35+
print(f"Loaded {len(message.data['mcp_servers'])} MCP servers")
36+
elif isinstance(message, AssistantMessage):
37+
for block in message.content:
38+
if isinstance(block, TextBlock):
39+
print(f"Claude: {block.text}")
40+
41+
42+
async def strict_mcp_config_example():
43+
"""Example using strict MCP configuration to ignore file-based configs."""
44+
print("\n=== Strict MCP Config Example ===")
45+
46+
# This ensures ONLY the MCP servers specified here will be used,
47+
# ignoring any global or project-level MCP configurations
48+
options = ClaudeCodeOptions(
49+
mcp_servers={
50+
"my-custom-server": {
51+
"command": "node",
52+
"args": ["my-mcp-server.js"],
53+
}
54+
},
55+
strict_mcp_config=True, # Ignore all file-based MCP configurations
56+
)
57+
58+
async for message in query(
59+
prompt="List the available MCP tools",
60+
options=options,
61+
):
62+
if isinstance(message, SystemMessage) and message.subtype == "init":
63+
if "mcp_servers" in message.data:
64+
servers = message.data["mcp_servers"]
65+
print(f"Loaded exactly {len(servers)} MCP servers (strict mode)")
66+
for server in servers:
67+
print(f" - {server['name']}")
68+
elif isinstance(message, AssistantMessage):
69+
for block in message.content:
70+
if isinstance(block, TextBlock):
71+
print(f"Claude: {block.text}")
72+
73+
74+
async def multiple_mcp_servers_example():
75+
"""Example with multiple MCP servers."""
76+
print("\n=== Multiple MCP Servers Example ===")
77+
78+
options = ClaudeCodeOptions(
79+
mcp_servers={
80+
"filesystem": {
81+
"command": "npx",
82+
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"],
83+
},
84+
"github": {
85+
"command": "npx",
86+
"args": ["-y", "@modelcontextprotocol/server-github"],
87+
"env": {
88+
"GITHUB_PERSONAL_ACCESS_TOKEN": "your-token-here"
89+
}
90+
}
91+
}
92+
)
93+
94+
async for message in query(
95+
prompt="What MCP servers and tools do I have access to?",
96+
options=options,
97+
):
98+
if isinstance(message, AssistantMessage):
99+
for block in message.content:
100+
if isinstance(block, TextBlock):
101+
print(f"Claude: {block.text}")
102+
103+
104+
async def main():
105+
"""Run MCP examples."""
106+
print("MCP (Model Context Protocol) Server Examples\n")
107+
print("Note: These examples require MCP servers to be installed.")
108+
print("See: https://github.com/modelcontextprotocol\n")
109+
110+
# Run basic example
111+
await basic_mcp_server_example()
112+
113+
# Uncomment to run other examples:
114+
# await strict_mcp_config_example()
115+
# await multiple_mcp_servers_example()
116+
117+
118+
if __name__ == "__main__":
119+
anyio.run(main)

examples/quick_start.py

Lines changed: 0 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -43,64 +43,10 @@ async def with_options_example():
4343
print()
4444

4545

46-
async def with_tools_example():
47-
"""Example using tools."""
48-
print("=== With Tools Example ===")
49-
50-
options = ClaudeCodeOptions(
51-
allowed_tools=["Read", "Write"],
52-
system_prompt="You are a helpful file assistant.",
53-
)
54-
55-
async for message in query(
56-
prompt="Create a file called hello.txt with 'Hello, World!' in it",
57-
options=options,
58-
):
59-
if isinstance(message, AssistantMessage):
60-
for block in message.content:
61-
if isinstance(block, TextBlock):
62-
print(f"Claude: {block.text}")
63-
elif isinstance(message, ResultMessage) and message.total_cost_usd > 0:
64-
print(f"\nCost: ${message.total_cost_usd:.4f}")
65-
print()
66-
67-
68-
async def with_strict_mcp_config_example():
69-
"""Example using strict MCP configuration."""
70-
print("=== Strict MCP Config Example ===")
71-
72-
# This ensures ONLY the MCP servers specified here will be used,
73-
# ignoring any global or project-level MCP configurations
74-
options = ClaudeCodeOptions(
75-
mcp_servers={
76-
"memory-server": {
77-
"command": "npx",
78-
"args": ["@modelcontextprotocol/server-memory"],
79-
}
80-
},
81-
strict_mcp_config=True, # Ignore all file-based MCP configurations
82-
)
83-
84-
async for message in query(
85-
prompt="List the available MCP tools from the memory server",
86-
options=options,
87-
):
88-
if isinstance(message, AssistantMessage):
89-
for block in message.content:
90-
if isinstance(block, TextBlock):
91-
print(f"Claude: {block.text}")
92-
elif isinstance(message, ResultMessage):
93-
print(f"\nResult: {message.subtype}")
94-
print()
95-
96-
9746
async def main():
9847
"""Run all examples."""
9948
await basic_example()
10049
await with_options_example()
101-
await with_tools_example()
102-
# Note: Uncomment the line below if you have MCP servers configured
103-
# await with_strict_mcp_config_example()
10450

10551

10652
if __name__ == "__main__":

examples/using_tools.py

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
#!/usr/bin/env python3
2+
"""Example demonstrating how to use tools with Claude Code SDK."""
3+
4+
import anyio
5+
6+
from claude_code_sdk import (
7+
AssistantMessage,
8+
ClaudeCodeOptions,
9+
ResultMessage,
10+
TextBlock,
11+
ToolResultBlock,
12+
ToolUseBlock,
13+
query,
14+
)
15+
16+
17+
async def file_operations_example():
18+
"""Example using file tools."""
19+
print("=== File Operations Example ===")
20+
21+
options = ClaudeCodeOptions(
22+
allowed_tools=["Read", "Write"],
23+
system_prompt="You are a helpful file assistant.",
24+
)
25+
26+
async for message in query(
27+
prompt="Create a file called hello.txt with 'Hello, World!' in it",
28+
options=options,
29+
):
30+
if isinstance(message, AssistantMessage):
31+
for block in message.content:
32+
if isinstance(block, TextBlock):
33+
print(f"Claude: {block.text}")
34+
elif isinstance(block, ToolUseBlock):
35+
print(f"\nUsing tool: {block.name}")
36+
print(f"Input: {block.input}")
37+
elif isinstance(message, ResultMessage):
38+
print(f"\nResult: {message.subtype}")
39+
if message.total_cost_usd and message.total_cost_usd > 0:
40+
print(f"Cost: ${message.total_cost_usd:.4f}")
41+
42+
43+
async def code_editing_example():
44+
"""Example using code editing tools."""
45+
print("\n=== Code Editing Example ===")
46+
47+
# First create a Python file
48+
options = ClaudeCodeOptions(
49+
allowed_tools=["Write", "Edit", "Read"],
50+
)
51+
52+
async for message in query(
53+
prompt="Create a simple Python function that calculates factorial in a file called factorial.py",
54+
options=options,
55+
):
56+
if isinstance(message, AssistantMessage):
57+
for block in message.content:
58+
if isinstance(block, TextBlock):
59+
print(f"Claude: {block.text}")
60+
61+
62+
async def bash_command_example():
63+
"""Example using bash commands."""
64+
print("\n=== Bash Command Example ===")
65+
66+
options = ClaudeCodeOptions(
67+
allowed_tools=["Bash"],
68+
permission_mode="acceptEdits", # Auto-accept commands for this example
69+
)
70+
71+
async for message in query(
72+
prompt="Show me the current directory contents using ls -la",
73+
options=options,
74+
):
75+
if isinstance(message, AssistantMessage):
76+
for block in message.content:
77+
if isinstance(block, TextBlock):
78+
print(f"Claude: {block.text}")
79+
elif isinstance(block, ToolUseBlock) and block.name == "Bash":
80+
print(f"\nRunning command: {block.input.get('command', '')}")
81+
82+
83+
async def main():
84+
"""Run tool examples."""
85+
await file_operations_example()
86+
await code_editing_example()
87+
await bash_command_example()
88+
89+
90+
if __name__ == "__main__":
91+
anyio.run(main)

0 commit comments

Comments
 (0)