Docs: Update CallToolResult parsing in README (#812)
Co-authored-by: Felix Weinberger <fweinberger@anthropic.com>
This commit is contained in:
parent
c0bc6668c4
commit
dd792977dd
2 changed files with 130 additions and 0 deletions
70
README.md
70
README.md
|
|
@ -44,6 +44,7 @@
|
||||||
- [Advanced Usage](#advanced-usage)
|
- [Advanced Usage](#advanced-usage)
|
||||||
- [Low-Level Server](#low-level-server)
|
- [Low-Level Server](#low-level-server)
|
||||||
- [Writing MCP Clients](#writing-mcp-clients)
|
- [Writing MCP Clients](#writing-mcp-clients)
|
||||||
|
- [Parsing Tool Results](#parsing-tool-results)
|
||||||
- [MCP Primitives](#mcp-primitives)
|
- [MCP Primitives](#mcp-primitives)
|
||||||
- [Server Capabilities](#server-capabilities)
|
- [Server Capabilities](#server-capabilities)
|
||||||
- [Documentation](#documentation)
|
- [Documentation](#documentation)
|
||||||
|
|
@ -1605,6 +1606,75 @@ async def main():
|
||||||
|
|
||||||
For a complete working example, see [`examples/clients/simple-auth-client/`](examples/clients/simple-auth-client/).
|
For a complete working example, see [`examples/clients/simple-auth-client/`](examples/clients/simple-auth-client/).
|
||||||
|
|
||||||
|
### Parsing Tool Results
|
||||||
|
|
||||||
|
When calling tools through MCP, the `CallToolResult` object contains the tool's response in a structured format. Understanding how to parse this result is essential for properly handling tool outputs.
|
||||||
|
|
||||||
|
```python
|
||||||
|
"""examples/snippets/clients/parsing_tool_results.py"""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
|
||||||
|
from mcp import ClientSession, StdioServerParameters, types
|
||||||
|
from mcp.client.stdio import stdio_client
|
||||||
|
|
||||||
|
|
||||||
|
async def parse_tool_results():
|
||||||
|
"""Demonstrates how to parse different types of content in CallToolResult."""
|
||||||
|
server_params = StdioServerParameters(
|
||||||
|
command="python", args=["path/to/mcp_server.py"]
|
||||||
|
)
|
||||||
|
|
||||||
|
async with stdio_client(server_params) as (read, write):
|
||||||
|
async with ClientSession(read, write) as session:
|
||||||
|
await session.initialize()
|
||||||
|
|
||||||
|
# Example 1: Parsing text content
|
||||||
|
result = await session.call_tool("get_data", {"format": "text"})
|
||||||
|
for content in result.content:
|
||||||
|
if isinstance(content, types.TextContent):
|
||||||
|
print(f"Text: {content.text}")
|
||||||
|
|
||||||
|
# Example 2: Parsing structured content from JSON tools
|
||||||
|
result = await session.call_tool("get_user", {"id": "123"})
|
||||||
|
if hasattr(result, "structuredContent") and result.structuredContent:
|
||||||
|
# Access structured data directly
|
||||||
|
user_data = result.structuredContent
|
||||||
|
print(f"User: {user_data.get('name')}, Age: {user_data.get('age')}")
|
||||||
|
|
||||||
|
# Example 3: Parsing embedded resources
|
||||||
|
result = await session.call_tool("read_config", {})
|
||||||
|
for content in result.content:
|
||||||
|
if isinstance(content, types.EmbeddedResource):
|
||||||
|
resource = content.resource
|
||||||
|
if isinstance(resource, types.TextResourceContents):
|
||||||
|
print(f"Config from {resource.uri}: {resource.text}")
|
||||||
|
elif isinstance(resource, types.BlobResourceContents):
|
||||||
|
print(f"Binary data from {resource.uri}")
|
||||||
|
|
||||||
|
# Example 4: Parsing image content
|
||||||
|
result = await session.call_tool("generate_chart", {"data": [1, 2, 3]})
|
||||||
|
for content in result.content:
|
||||||
|
if isinstance(content, types.ImageContent):
|
||||||
|
print(f"Image ({content.mimeType}): {len(content.data)} bytes")
|
||||||
|
|
||||||
|
# Example 5: Handling errors
|
||||||
|
result = await session.call_tool("failing_tool", {})
|
||||||
|
if result.isError:
|
||||||
|
print("Tool execution failed!")
|
||||||
|
for content in result.content:
|
||||||
|
if isinstance(content, types.TextContent):
|
||||||
|
print(f"Error: {content.text}")
|
||||||
|
|
||||||
|
|
||||||
|
async def main():
|
||||||
|
await parse_tool_results()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
asyncio.run(main())
|
||||||
|
```
|
||||||
|
|
||||||
### MCP Primitives
|
### MCP Primitives
|
||||||
|
|
||||||
The MCP protocol defines three core primitives that servers can implement:
|
The MCP protocol defines three core primitives that servers can implement:
|
||||||
|
|
|
||||||
60
examples/snippets/clients/parsing_tool_results.py
Normal file
60
examples/snippets/clients/parsing_tool_results.py
Normal file
|
|
@ -0,0 +1,60 @@
|
||||||
|
"""examples/snippets/clients/parsing_tool_results.py"""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
|
||||||
|
from mcp import ClientSession, StdioServerParameters, types
|
||||||
|
from mcp.client.stdio import stdio_client
|
||||||
|
|
||||||
|
|
||||||
|
async def parse_tool_results():
|
||||||
|
"""Demonstrates how to parse different types of content in CallToolResult."""
|
||||||
|
server_params = StdioServerParameters(command="python", args=["path/to/mcp_server.py"])
|
||||||
|
|
||||||
|
async with stdio_client(server_params) as (read, write):
|
||||||
|
async with ClientSession(read, write) as session:
|
||||||
|
await session.initialize()
|
||||||
|
|
||||||
|
# Example 1: Parsing text content
|
||||||
|
result = await session.call_tool("get_data", {"format": "text"})
|
||||||
|
for content in result.content:
|
||||||
|
if isinstance(content, types.TextContent):
|
||||||
|
print(f"Text: {content.text}")
|
||||||
|
|
||||||
|
# Example 2: Parsing structured content from JSON tools
|
||||||
|
result = await session.call_tool("get_user", {"id": "123"})
|
||||||
|
if hasattr(result, "structuredContent") and result.structuredContent:
|
||||||
|
# Access structured data directly
|
||||||
|
user_data = result.structuredContent
|
||||||
|
print(f"User: {user_data.get('name')}, Age: {user_data.get('age')}")
|
||||||
|
|
||||||
|
# Example 3: Parsing embedded resources
|
||||||
|
result = await session.call_tool("read_config", {})
|
||||||
|
for content in result.content:
|
||||||
|
if isinstance(content, types.EmbeddedResource):
|
||||||
|
resource = content.resource
|
||||||
|
if isinstance(resource, types.TextResourceContents):
|
||||||
|
print(f"Config from {resource.uri}: {resource.text}")
|
||||||
|
elif isinstance(resource, types.BlobResourceContents):
|
||||||
|
print(f"Binary data from {resource.uri}")
|
||||||
|
|
||||||
|
# Example 4: Parsing image content
|
||||||
|
result = await session.call_tool("generate_chart", {"data": [1, 2, 3]})
|
||||||
|
for content in result.content:
|
||||||
|
if isinstance(content, types.ImageContent):
|
||||||
|
print(f"Image ({content.mimeType}): {len(content.data)} bytes")
|
||||||
|
|
||||||
|
# Example 5: Handling errors
|
||||||
|
result = await session.call_tool("failing_tool", {})
|
||||||
|
if result.isError:
|
||||||
|
print("Tool execution failed!")
|
||||||
|
for content in result.content:
|
||||||
|
if isinstance(content, types.TextContent):
|
||||||
|
print(f"Error: {content.text}")
|
||||||
|
|
||||||
|
|
||||||
|
async def main():
|
||||||
|
await parse_tool_results()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
asyncio.run(main())
|
||||||
Loading…
Reference in a new issue