MCP: A Standard Way to Offer Tools

The Model Context Protocol lets any AI app discover and call tools from any server. Build a tiny server that answers tools/list and tools/call.

AI · intermediate · 7 min · 19 steps · free

What you'll learn

mcp_server.py

import json

# A tiny stand-in for an MCP server: it lists its tools and runs them when asked.
class WeatherServer:
    def handle(self, request):
        if request['method'] == 'tools/list':
            return {'tools': [{'name': 'get_weather', 'params': ['city']}]}
        if request['method'] == 'tools/call':
            city = request['params']['arguments']['city']
            return {'content': f'{city}: 31 C, sunny'}
        return {'error': 'unknown method'}

server = WeatherServer()
listing = server.handle({'method': 'tools/list'})
print(json.dumps(listing))
call = {'method': 'tools/call', 'params': {'name': 'get_weather', 'arguments': {'city': 'Chennai'}}}
reply = server.handle(call)
print(reply['content'])

Step by step

  1. This brings in Python's built-in json module, so the program can use the functions it provides.
  2. Python starts building the class WeatherServer. Its methods are stored, but none of them run yet.
  3. Python reads the class body: everything indented under class WeatherServer belongs to it.
  4. The server is a class that handles requests.
  5. The class WeatherServer is now defined, ready to make objects from.
  6. server is created and points to a new WeatherServer: {}.
  7. tools/list: the client asks what this server can do.
  8. request['method'] == 'tools/list' is true, so the block under it runs.
  9. The function returns {'tools': [{'name': 'get_weather', 'params': ['city']}]}.
  10. handle() has finished, so its names are gone. The value it returned, {tools: a list}, is stored in listing.
  11. The answer lists each tool with its parameters. A client shows these to its model.
  12. call is created and points to a new dict: {method: 'tools/call', params: a dict}.
  13. tools/call: run get_weather for Chennai.
  14. request['method'] == 'tools/list' is false, so the block under it is skipped.
  15. request['method'] == 'tools/call' is true, so the block under it runs.
  16. city is created with the value 'Chennai'.
  17. The function returns {'content': f'{city}: 31 C, sunny'}.
  18. handle() has finished, so its names are gone. The value it returned, {content: 'Chennai: 31 C, sunny'}, is stored in reply.
  19. The result goes back to the client, and from there into the model's context.

Common mistakes

Best practices

Key takeaways

Check yourself

Which message asks for available tools?

Answer: tools/list

MCP messages are?

Answer: JSON. JSON-RPC.

More in Agents in Production