Aan de slagGa gratis aan de slag

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.

Deze oefening maakt deel uit van de cursus

Introduction to Model Context Protocol (MCP)

Cursus bekijken

Oefeninstructies

  • Call the tool with the tool_name and arguments parameters 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).

Praktische interactieve oefening

Probeer deze oefening eens door deze voorbeeldcode in te vullen.

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"})
)
Code bewerken en uitvoeren