Skip to main content

Activity: Add API to server

A tool like add is interesting to see how things work, but the real value comes from seeing how to use it in a real application. In this activity, you will add an API to the server you created in the previous activity.

So far, you've seen how we added a simple tool like add to the server. But what if we want to call a Web API? In this activity, you will add an API to the server you created in the previous activity.

-1- Adding a tool calling an API

Let's create a file server-api.py

@mcp.tool()
async def joke() -> str:
"""Get joke"""
res = requests.get("https://api.chucknorris.io/jokes/random")
json_response = res.json()

return json_response.get("value", "No joke found.")

-2- Adding a tool that takes input

You saw how simply we can call an API, but what if we want to pass some input to the API?

@mcp.tool()
async def joke_param(category: str = "sport") -> str:
"""Get joke with parameter"""

res = requests.get(f"https://api.chucknorris.io/jokes/random?category={category}")
json_response = res.json()

return json_response.get("value", "No joke found.")

Here we add a new function joke_param and a parameter category.

-3- Testing the server

Get in the habit of testing the server after each change. You can do this in several ways:

  • Calling the inspector tool npx @modelcontextprotocol/inspector node build/index.js.
  • You can also use a tool like curl or Postman to call the API directly (if this is a server using SSE or streamable HTTP). For example, you can call the API using curl like this:
curl -X POST -H "Content-Type: application/json" -d '{"category": ["dev"]}' http://localhost:3000/random-joke-by-category

Run the first tool:

npx @modelcontextprotocol/inspector --cli mcp run server-api.py --method tools/call --tool-name joke

Run the second tool with a param

npx @modelcontextprotocol/inspector --cli mcp run server-api.py --method tools/call --tool-name joke_param --tool-arg category=travel

-4- Summary

You've learned to add an API in one of your tools. You can either add this code to your existing server, if you created from the previous activity, or you can work in that code into below GitHub repository:

git clone https://github.com/softchris/mcp-workshop.git
cd mcp-workshop

Follow the instructions in the README file.