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
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'])json module, so the program can use the functions it provides.WeatherServer. Its methods are stored, but none of them run yet.class WeatherServer belongs to it.WeatherServer is now defined, ready to make objects from.server is created and points to a new WeatherServer: {}.tools/list: the client asks what this server can do.request['method'] == 'tools/list' is true, so the block under it runs.{'tools': [{'name': 'get_weather', 'params': ['city']}]}.handle() has finished, so its names are gone. The value it returned, {tools: a list}, is stored in listing.call is created and points to a new dict: {method: 'tools/call', params: a dict}.tools/call: run get_weather for Chennai.request['method'] == 'tools/list' is false, so the block under it is skipped.request['method'] == 'tools/call' is true, so the block under it runs.city is created with the value 'Chennai'.{'content': f'{city}: 31 C, sunny'}.handle() has finished, so its names are gone. The value it returned, {content: 'Chennai: 31 C, sunny'}, is stored in reply.Answer: tools/list
Answer: JSON. JSON-RPC.
← Handling Tool Failures with Retries