Tutorial · AI agents on social media

How to build an MCP server: tools, transport and the first client call

By Antoine Blanco··7 min read

An MCP server is a program that answers tools/list with a list of tools and tools/call by running one. With the Python SDK that is twelve lines. Everything below ran today, November 20, 2026, on mcp 2.3.0 against protocol revision 2026-07-28, raw output included.

What an MCP server has to answer

Three things, and only the first is mandatory.

A server declares capabilities (tools, resources, prompts), answers tools/list with a deterministic set of tool definitions, and answers tools/call by running one and returning content. Resources and prompts are optional. Most servers worth writing are a bag of tools and nothing else.

A tool definition needs a name, a description and an inputSchema that is a valid JSON Schema object. title, outputSchema and annotations are optional. The tools specification says names should be 1 to 128 characters from letters, digits, underscore, hyphen and dot, and unique inside the server. For a tool with no arguments, the recommended schema is {"type": "object", "additionalProperties": false}, never null.

Create an MCP server with the MCP Python SDK

Install the SDK and its CLI extra:

pip install "mcp[cli]"      # or: uv add "mcp[cli]"

That is mcp 2.3.0, published on PyPI on October 2, 2026. The entry point is MCPServer, which replaced the old FastMCP name:

from mcp.server import MCPServer

mcp = MCPServer("word-count", version="1.0.0")


@mcp.tool()
def count_words(text: str) -> int:
    """Count the words in a block of text."""
    return len(text.split())


if __name__ == "__main__":
    mcp.run()

Three things happen without you writing them. The docstring becomes the tool description, which is the only thing the model reads to decide whether to call it, so write it for the model and not for your colleagues. The type hints become the inputSchema. And the return annotation becomes an outputSchema, so the result arrives as structured JSON, not just text.

Test it before you wire any client:

mcp dev server.py

That opens the MCP Inspector, which lists the tools and lets you call them by hand. It is the fastest way to find out that an argument name you thought was obvious is not.

stdio or Streamable HTTP

mcp.run() defaults to stdio. The 2026-07-28 revision defines exactly two standard transports, and the choice is about who runs the process, not about features: protocol semantics are identical on every transport.

stdio Streamable HTTP
Who starts it the client, as a subprocess you, as a service
Framing newline-delimited JSON-RPC on stdin and stdout one HTTP POST per message
Reaches other people no yes
Auth inherits the local process OAuth or an API key
Cancellation notifications/cancelled the client closes the stream
Right for a tool on your own machine anything other people use

One rule people break on day one: on stdio, stdout belongs to the protocol. A stray print() corrupts the stream. Log to stderr.

Switch transport with one argument:

mcp.run(transport="streamable-http")
INFO  StreamableHTTP session manager started
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)

The endpoint is /mcp, so http://127.0.0.1:8000/mcp.

The first client call, for real

Point the SDK's own client at the stdio server:

import asyncio, sys
from mcp import Client, StdioServerParameters

async def main():
    params = StdioServerParameters(command=sys.executable, args=["server.py"])
    async with Client(params) as client:
        print("protocol:", client.protocol_version)
        tools = await client.list_tools()
        for t in tools.tools:
            print("tool:", t.name, "|", t.description)
        res = await client.call_tool("count_words", {"text": "one two three four"})
        print("content:", res.content)
        print("structured:", res.structured_content)

asyncio.run(main())

What it printed:

protocol: 2026-07-28
tool: count_words | Count the words in a block of text.
content: [TextContent(type='text', text='4', annotations=None, meta=None)]
structured: {'result': 4}

Note the two spellings. The wire format is camelCase (inputSchema, structuredContent, isError); the Python objects are snake_case (input_schema, structured_content, is_error). Reading t.inputSchema raises AttributeError, which is where I lost my first five minutes.

Over HTTP, curl needs four headers, and getting them wrong is the whole debugging session:

curl -s -X POST http://127.0.0.1:8000/mcp \
  -H 'Content-Type: application/json' \
  -H 'Accept: application/json, text/event-stream' \
  -H 'MCP-Protocol-Version: 2026-07-28' \
  -H 'mcp-method: tools/list' \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{"_meta":{
       "io.modelcontextprotocol/protocolVersion":"2026-07-28",
       "io.modelcontextprotocol/clientCapabilities":{}}}}'
{"jsonrpc":"2.0","id":1,"result":{"cacheScope":"private","resultType":"complete",
 "tools":[{"description":"Count the words in a block of text.",
 "inputSchema":{"type":"object","properties":{"text":{"title":"Text","type":"string"}},
 "required":["text"],"title":"count_wordsArguments"},"name":"count_words",
 "outputSchema":{"properties":{"result":{"title":"Result","type":"integer"}},
 "required":["result"],"type":"object"}}],"ttlMs":0}}

Two errors you will hit in that order. Drop _meta and you get -32602: params._meta must be an object carrying the required 'io.modelcontextprotocol/protocolVersion' and 'io.modelcontextprotocol/clientCapabilities' envelope keys. Keep _meta but omit the header and you get -32020: mcp-method header does not match the request body's method. A tools/call needs a third one, mcp-name, carrying the tool name, or the same -32020 comes back.

With all of them, the call returns both shapes:

{"id":2,"result":{"content":[{"text":"4","type":"text"}],"isError":false,
 "resultType":"complete","structuredContent":{"result":4}}}

What the 2026-07-28 revision changed

If you are following a tutorial written against 2025-06-18 or 2025-11-25, three things moved.

There is no initialize handshake. Every request declares its own protocol version and client capabilities in params._meta, and the server accepts or rejects each request independently. Streamable HTTP mirrors those values into headers so a proxy can route without parsing the body, and the body stays the source of truth.

Discovery is a single optional call. server/discover returns the supported versions, the capabilities and the identity at once:

{"id":3,"result":{"capabilities":{"prompts":{"listChanged":true},
 "resources":{"listChanged":true,"subscribe":true},"tools":{"listChanged":true}},
 "supportedVersions":["2026-07-28"]}}

And there is no protocol session. A server cannot keep per-connection state, so anything spanning calls has to be an explicit handle you return from one tool and accept as an argument on the next. Send an old-style request to this server and it falls back to the session-based path, which answers Bad Request: Missing session ID. That is backwards compatibility working, not a bug. What it means for deployment is in MCP server hosting.

The error path that teaches the model

The spec splits errors in two. A malformed request or an unknown method is a JSON-RPC error. A failure the model could fix by retrying differently is a tool result with isError: true, because clients pass those back to the model and it can self-correct.

The SDK gets this almost right by itself. An unknown tool returns a result, not a protocol error:

{"id":4,"result":{"content":[{"text":"Unknown tool: nope","type":"text"}],"isError":true}}

But raise an exception inside a tool and the message is swallowed:

raise ValueError("text is empty, pass at least one word")
is_error: True
content: Error executing tool count_words

The model now knows the call failed and nothing about why, so it retries the same arguments. If you want the model to fix itself, return the explanation as the tool's own text instead of raising. That one habit is worth more than any schema work.

Before you let an agent near it

A server that works on your laptop is not a server you hand to someone else. Two pieces are missing, and both have their own page here: authentication, covered in MCP server OAuth, and the hosting decision. The specification is blunt about the rest: validate every input, rate limit invocations, and never mark a secret with x-mcp-header, because header values are visible to every intermediary on the path.

It is also worth asking whether you should write the server at all. For something like social publishing, the hard part is not MCP, it is eight platform APIs, eight OAuth flows and token refresh: that is why PlugKit runs a hosted MCP server at https://api.plugkit.co/mcp instead of shipping a template, at $49 a month for 5 connected accounts, cancel anytime, or $97 a month for 30, after seven free days with a card at sign-up and nothing charged before day 7. Checked on November 20, 2026. Write your own when the tools are yours: your database, your internal API, your build system. MCP or REST API for your agent is the decision one level up, and Instagram MCP server is what the finished thing looks like from the client side.

FAQ

What language should I build an MCP server in?

Whichever one your tools already live in. The official SDK list has ten: TypeScript, Python, C#, Go, Rust and Ruby at tier 1, Java at tier 2, Swift, PHP and Kotlin at tier 3, where the tier is how complete and how maintained it is. They all speak the same JSON-RPC. The server is a thin wrapper around code you already have, so rewriting that code in another language is the expensive mistake.

Do I need Streamable HTTP, or is stdio enough?

stdio is enough when the only user is you on this machine: the client launches your script as a subprocess and nothing is exposed. The moment a second person or a hosted agent needs it, you need Streamable HTTP, a URL and authentication.

How do I test an MCP server without a client?

mcp dev server.py opens the MCP Inspector, which lists your tools and calls them with arguments you type. After that, curl against the HTTP endpoint shows the exact JSON a real client sends, which is how you catch a schema the model will misread.

Why does my tool work in the Inspector but not in the agent?

Usually the description. The model picks tools by reading description and the argument titles, and a docstring like "handles the thing" gives it nothing to match on. Rewrite the docstring as an instruction, state what the tool returns, and name arguments the way a caller would guess them.

How many tools should one MCP server expose?

Fewer than you want to. Every definition sits in the model's context on every turn, so a hundred tools costs real tokens and real confusion between near-duplicates. Group by job, return structured content so one tool can answer several questions, and split into separate servers before you split a server into a hundred names.

AB
Antoine BlancoFounder of PlugKit. Runs his own Instagram, YouTube and X accounts through the API and MCP server described here.

One plug for every platform your agent touches

$49 a month for 5 connected accounts, cancel anytime. Every feature in every plan.

Get your API key →
English ▾