Calling Server Tools
Now to trigger tool calls in the server from your client! Again, you'll be using asynchronous operations to ensure that nothing breaks or freezes while waiting for other operations to complete.
Este ejercicio forma parte del curso
Introduction to Model Context Protocol (MCP)
Instrucciones del ejercicio
- Call the tool with the
tool_nameandargumentsparameters specified by the user; ensure that the call pauses to wait for the server to respond using the appropriate Python keyword. - Extract and print the text content of the server response.
- Run the
"convert_currency"tool with a set of valid parameters (use whatever values and currencies you wish here).
Ejercicio interactivo práctico
Prueba este ejercicio y completa el código de muestra.
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
async def call_mcp_tool(tool_name: str, arguments: dict) -> str:
params = StdioServerParameters(
command=sys.executable,
args=["currency_server.py"],
)
async with stdio_client(params) as (reader, writer):
async with ClientSession(reader, writer) as session:
await session.initialize()
# Call the currency conversion tool
result = ____ ____(tool_name, arguments)
# Extract and print the text content of the server response
text_content = result.____[0].____
print(f"Conversion Result: {text_content}")
return text_content
# Run the "convert_currency" tool
asyncio.run(
call_mcp_tool("convert_currency",
{"amount": 250.0, "from_currency": "USD", "to_currency": "EUR"})
)