# agent.py: a one-tool Claude Agent SDK agent. # Pattern adapted from the README of anthropics/claude-agent-sdk-python (MIT), # pinned at commit 6b4a557e9f395934bd16e78b04e0f09833eb387e (v0.2.172). import asyncio from claude_agent_sdk import ( ClaudeAgentOptions, ClaudeSDKClient, ResultMessage, create_sdk_mcp_server, tool, ) @tool("word_count", "Count the words in a block of text", {"text": str}) async def word_count(args): count = len(args["text"].split()) return {"content": [{"type": "text", "text": f"{count} words"}]} counter = create_sdk_mcp_server(name="counter", version="1.0.0", tools=[word_count]) options = ClaudeAgentOptions( mcp_servers={"counter": counter}, tools=[], # remove every built-in tool allowed_tools=["mcp__counter__word_count"], # pre-approve the one tool permission_mode="dontAsk", # deny anything not pre-approved setting_sources=[], # ignore local Claude Code settings env={ "ENABLE_TOOL_SEARCH": "false", # load the tool schema up front "CLAUDE_CODE_DISABLE_AUTO_MEMORY": "1", # keep auto memory out of the prompt }, system_prompt="You count words. Always use the word_count tool, then report the number.", max_turns=4, ) async def main(): async with ClaudeSDKClient(options=options) as client: await client.query( "How many words are in: the quick brown fox jumps over the lazy dog" ) async for message in client.receive_response(): print(message) if isinstance(message, ResultMessage): # subtype "success" alone is not enough: an API error or a # refusal also arrives as success with is_error=True. ok = ( message.subtype == "success" and not message.is_error and message.terminal_reason == "completed" ) print("RUN OK" if ok else f"RUN FAILED: {message.terminal_reason} {message.result}") if __name__ == "__main__": asyncio.run(main())