Single logo
  • Courses
  • Blog
  • About
Join free on SkoolJoin free on Skool

In this topic

AI Engineering
  • The AI Stack in One Picture: Six Layers Every AI Product Is Built From
  • Tokenization: What an LLM Actually Sees When You Type
  • LLM Tokens, Context Windows and Cost: What One Question Really Costs
  • What an LLM Can and Cannot Do: One Prediction Loop, Its Strengths and Its Gaps
  • Structured LLM Output with Pydantic: Describe the Shape Once, Check Every Reply
  • Temperature, Top-p and Sampling: Why the Same Prompt Gives a Different Answer
  • Open vs Closed LLMs: Cost, Control, Privacy and Capability, Decided per Workload
  • Streaming and Error Handling for LLM Calls: Show the First Word Early, Retry Politely, Fail Calmly
  • Practice: Build a CLI Chat Tool with Memory, Commands, Error Handling and a History Cap
  • Explicit Criteria vs Vague Prompts: Turn Every Adjective Into a Check a Script Can Run
  • Few-Shot Prompting Done Right: How Many Examples, How Different, What Order, and the Leak That Lies
  • Prompt Caching: Keep the Start of Every Request Identical and Pay for the Long Part Once
  • Prompt Versioning and Testing in a Repo: Prompt Files, a Registry, a Hash per Answer and Tests That Gate
  • Context Engineering: What Belongs in the Context Window, Turn by Turn
  • Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It
  • What an Embedding Actually Is: Meaning as Numbers, Search by Closeness, and Where Hand-Made Numbers Break
  • The RAG Pipeline Explained: 7 Stages From Documents to a Cited Answer
  • Similarity Search: Finding the Closest Vectors with NumPy and NearestNeighbors
  • Why RAG Exists: The Problem It Solves, Compared With Pasting Everything and Fine-Tuning
  • Real Embedding Models: an Open Model or a Provider API, Then Search, Duplicates and Recommendations
  • Chunking Strategies for RAG: Fixed Size, Sentences or Headings, Measured on One Handbook
  • Vector Databases Hands-On: The Same Search in Chroma and pgvector
  • RAG Prompt Assembly and Citations: Number the Blocks, Fit a Token Budget, Check Every Claim
  • Hybrid Search: BM25 Plus Dense Embeddings, Merged With Reciprocal Rank Fusion
  • Reranking With a Cross-Encoder: When the Second Pass Helps, and When It Doesn't
  • Retrieval Evals: Score the Retriever With Recall@K, MRR and nDCG Before Blaming the Model
  • Choosing a Vector Index: Flat, HNSW or IVF-PQ, a Memory Estimate, and Filters That Starve Small Customers
  • Citations and Abstention in RAG: What a Citation Proves, and When the Right Answer Is "It's Not in the Documents"
  • Embedding Migration With Zero Downtime: Two Indexes, a Dual-Write Backfill, a Shadow Check and a Flag
  • Cosine, Dot Product or Euclidean Distance: Why Three Measures Pick Three Winners, and the One Fix
  • Choosing an Embedding Model: Dimension, Context Length, Domain and Cost, Tested on Your Own Questions
  • Loading and Parsing Real Documents for RAG: PDF Headers, Wrapped Lines, Tables and HTML Chrome, Scored
  • Where Naive RAG Fails: Five Ways the Simplest Retriever Hands the Model the Wrong Pages
  • RAG Generation Metrics: Faithfulness, Groundedness and Relevance, One Claim at a Time
  • Capstone: A Production RAG Service Over the Python Standard Library, With an Eval a Hiring Manager Can Rerun
  • Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It
  • What LangChain Is For, and When to Skip It: Five Standard Parts, One Pipe, and a Decision Table
  • Why Chains Break: No Branch, No Retry, No Pause, and the Same Refund Assistant as a LangGraph Graph
  • LangGraph Nodes, Edges and State: Build Your First Graph, Route With a Conditional Edge, and Read the Run Three Ways
  • Human-in-the-Loop and Checkpointing in LangGraph: interrupt, a SQLite Save Slot and Command(resume=...)
  • Multi-Agent Patterns: Hub and Spoke in LangGraph, With Short Briefs, Owned Tools and a Retry the Hub Decides
  • A Research Agent in LangGraph: Plan, Search, Read, Write, and a Check Node That Rejects Citations Nobody Read
  • What Is MCP? One Plug Between AI Apps and Tools: Host, Client, Server and the Three Messages
  • Configuring MCP Servers in Claude Code: A Command or a URL, Three Scopes, and Three Moves When One Breaks
  • Workflow or Agent: Decide Who Picks the Next Step, Then Let the Constraints Choose the Design
  • Custom Agent Loops and Harnesses: A Dispatch Table, an Approval Hold, Error Results and a Turn Budget
  • Building an MCP Server: Tools, Resources and Prompts in Python and TypeScript
  • MCP Transports: stdio or Streamable HTTP, and Who Starts the Server
  • Deploying and Authenticating an MCP Server: Environment Keys for stdio, Bearer Tokens and Scopes for HTTP
  • From ML Metrics to LLM Evals: Same Ruler, New Targets
  • Why You Cannot Ship an LLM Feature Without an Eval: Five Parts, Three Graders, One Tiny Eval
  • Building a Golden Dataset for LLM Evals: Cases, a Schema, a Coverage Table and a Seeded Split
  • Retrieval Evals: Score the Retriever With Recall@K, MRR and nDCG Before Blaming the Model
  • Regression Testing an LLM Bot in CI: A Golden Set, Two pytest Gates and GitHub Actions
  • Testing a RAG Bot Before It Ships: Slices, a Release Gate per Slice, and the Week After
  • RAG Generation Metrics: Faithfulness, Groundedness and Relevance, One Claim at a Time
  • LLM-as-Judge: Write a Rubric, Check Every Verdict, and Trust the Grader Only After Kappa Says So
  • RAGAS and Custom Evals: Framework Faithfulness Plus Your Own Citation and Required-Fact Checks, Behind One Gate
  • Which Test Layer Owns the Failure? Unit, Functional, Integration and End-to-End Tests for a Claude App
  • Six Ways a 200 Can Still Be Wrong: Hallucination, Refusal, Under-Acting, Context Loss, Format Drift and Inconsistency
  • Proving a Model Upgrade Is Ready: A Frozen Golden Set, a Calibrated Judge, the Right Layer and a Release Gate
  • Fallback Models for an LLM App: A Chain That Checks Region and Fit, Flags Degraded Answers and Gets Rehearsed
  • Back Pressure for LLM Traffic: Bound the Queue, Give Chat Its Own Lane, Count Tokens, Cancel When the Caller Leaves
  • Load Balancing LLM Traffic: Count the Work, Weigh the Prefix Cache, Check Real Health, Drain Before Deploys
  • A Message Queue for Document Ingestion: At Least Once, Leases, an Idempotent Consumer and a Dead Letter Queue
  • Caching for AI Apps: Four Layers, What Goes in Each Key, and How a Delete Travels
  • Semantic Caching: Why a Similarity Threshold Can't Stop Confident Wrong Answers
  • LLM Model Routing: Rules, a Classifier or a Cascade, Judged on Cost per Win and Every Topic
  • Cutting p95 and Cost in Half for an LLM App: Read the Bill, Match the Lever, Guard Success
  • Observability and Tracing for LLM Apps: A Span per Stage, Redaction First, Bad Traces Become Tests
  • Guardrails for an LLM Agent: Check What Comes In, What It Wants to Do, and What Goes Out
  • Embedding Migration With Zero Downtime: Two Indexes, a Dual-Write Backfill, a Shadow Check and a Flag
  • Design a Multi-Tenant RAG Assistant, Part 1: Requirements, Rough Numbers and a Contract
  • Design a Multi-Tenant RAG Assistant, Part 2: Tenant Isolation, a Scoped Cache and Walking an Outage
  • A 500 MB PDF Takes 50 s to Answer, Get It to 2 s: Measure First, Then Promise Per Path
  • A 500 MB PDF From 50 s to 2 s, the Fast Path: Queue, Status, Streaming and an Acceptance Test That Fails
  • FastAPI for AI Services: Schemas at the Door, Load Once in the Lifespan, Depends, and def vs async def
  • Streaming LLM Answers From FastAPI: Sources First, Token Events Over SSE, and the Same Events Over a WebSocket
  • Docker for AI Apps: Bake the Model Weights In at Build Time, Use CPU-Only PyTorch, and Run Offline
  • Deploy a RAG Service: A Service Key, Health and Ready Checks, Caddy in Front and a Smoke Test
  • Cost Tracking and Budget Guards for an LLM App: Count the Tokens, Log Every Call, Check Before You Spend
  • Versioning Prompts, Models and Indexes: Three Moving Parts, One Release File and a One-Line Rollback
  • Guardrails for an LLM Agent: Check What Comes In, What It Wants to Do, and What Goes Out
  • The Agent Attack Surface: Blast Radius, Narrow Tools, Scoped Keys and the Dangerous Three
  • Prompt Injection, Jailbreaks and Untrusted Input: Label What Comes In, Gate What Goes Out
  • Injection Exposure Review for an Agent: Map Inputs, Data and Effects, Layer Every Path, Retest the Job
  • Data Leakage and PII in LLM Apps: Redact, Minimize, Log Safely and Count Every Place
  • Hooks That Block Destructive Actions: a PreToolUse Gate That Allows, Asks or Denies
  • Claude API Keys: Keep the Key on a Server Proxy, One Key per Environment, Rotate and Scope It
  1. Blog
  2. /
  3. AI Engineering
  4. /
  5. Agents and MCP

Building an MCP Server: Tools, Resources and Prompts in Python and TypeScript

Build one small SupportDesk MCP server that offers a tool, a resource and a prompt, written in Python and in TypeScript, and check both with the same real MCP client.

Chaand Sheikh

·27 November 2026Agents and MCP

What you will learn

  • Explain what an MCP server offers and who controls each of its three kinds of things
  • Write a small MCP server with one tool, one resource and one prompt in Python and TypeScript
  • List and use a server's tools, resources and prompts from a real MCP client
  • Decide whether a capability should be a tool, a resource or a prompt

Before you start

  • Claude tool use: tool_use and tool_result
  • Basic Python

Picture a support team with its own orders and its own returns policy. A chat app wants that data. So does the support console, and so does the team bot. Without a shared standard, each app gets its own glue code, and you write the same connector three times.

The Model Context Protocol (MCP) fixes that. You write one MCP server that sits next to the data, and any app that speaks MCP can connect to it. In this article we build that server, called supportdesk, once in Python and once in TypeScript, and check both with the same client.

Where the server sits

An app (Claude Code, Claude Desktop or your own program) holds an MCP client. The part we build is the server. A request goes down: the client sends a tools/call with an order id. The answer comes back up: the server returns the status text and the client hands it to the app.

The server decides what it offers. The client only asks.

Three apps, one MCP server Chat app MCP client Support console MCP client Team bot MCP client supportdesk MCP server 1 tool, 1 resource, 1 prompt Orders Policies
Written once as a server, used by every client that speaks MCP.

Three kinds of things, three controllers

Think of the front desk of a help office. It has a filing cabinet you open and read, a service counter where you ask and someone does the job, and a pre-printed form you pick and fill in. In MCP those are a resource, a tool and a prompt. The difference that matters is who decides to use each one.

KindWhat it isWho decidesPythonCalls
ToolSomething that does a jobThe model calls it@mcp.tool()tools/list, tools/call
ResourceContent at a URI, to readThe app attaches it@mcp.resource(uri)resources/list, resources/read
PromptA ready-made requestThe user picks it@mcp.prompt()prompts/list, prompts/get

Each kind has a list call and a use call. The server only declares them; control sits with the model, the app or the user.

server.py: the whole server

Here is the complete Python server. Two made-up records stand in for the real data.

"""SupportDesk MCP server: one tool, one resource, one prompt, over stdio."""
from mcp.server import MCPServer

mcp = MCPServer("supportdesk")

ORDERS = {"A-1001": "shipped, arrives Friday"}
RETURNS = "Returns are accepted for 30 days if the item is unused."


@mcp.tool()
def order_status(order_id: str) -> str:
    """Look up the delivery status of one order by its id."""
    return ORDERS.get(order_id, "unknown order")


@mcp.resource("policy://returns")
def returns_policy() -> str:
    """The returns policy text."""
    return RETURNS


@mcp.prompt()
def ticket_summary(ticket_id: str) -> str:
    """A ready-made request: summarise one ticket."""
    return f"Summarise {ticket_id}."


if __name__ == "__main__":
    mcp.run(transport="stdio")
  • One server object with a name, supportdesk.
  • The tool decorator turns a plain function into something the model can call.
  • The resource has a URI, policy://returns, and returns the policy text.
  • The prompt takes a ticket id and returns a ready-made request.
  • The last line runs the server over standard input and output, so a client can start it as a process. The two transports get their own article.

The code writes the tool definition

The tool you just wrote is also a tool definition for Claude. The function name becomes the tool name, the docstring becomes the description, and the typed argument becomes the input_schema. Those are the same three fields you pass in the Messages API (see Claude tool use: tool_use and tool_result).

So the quality of the docstring is not a style point. It is the text Claude reads when it chooses a tool. A clear name, a clear docstring and a typed argument decide how well the model picks.

server.ts: the same server in TypeScript

Same three things with the TypeScript SDK. The input and argument schemas are zod objects.

import { McpServer } from "@modelcontextprotocol/server";
import { StdioServerTransport } from "@modelcontextprotocol/server/stdio";
import * as z from "zod/v4";

const server = new McpServer({ name: "supportdesk", version: "1.0.0" });
const ORDERS: Record<string, string> = { "A-1001": "shipped, arrives Friday" };
const RETURNS = "Returns are accepted for 30 days if the item is unused.";

server.registerTool(
  "order_status",
  {
    description: "Look up the delivery status of one order by its id.",
    inputSchema: z.object({ order_id: z.string() }),
  },
  async ({ order_id }) => ({
    content: [{ type: "text", text: ORDERS[order_id] ?? "unknown order" }],
  }),
);

server.registerResource(
  "returns_policy",
  "policy://returns",
  { description: "The returns policy text.", mimeType: "text/plain" },
  async (uri) => ({ contents: [{ uri: uri.href, text: RETURNS }] }),
);

server.registerPrompt(
  "ticket_summary",
  {
    description: "A ready-made request: summarise one ticket.",
    argsSchema: z.object({ ticket_id: z.string() }),
  },
  ({ ticket_id }) => ({
    messages: [
      { role: "user", content: { type: "text", text: `Summarise ${ticket_id}.` } },
    ],
  }),
);

await server.connect(new StdioServerTransport());

registerTool, registerResource and registerPrompt mirror the three Python decorators, and connect attaches the stdio transport.

A client lists, then uses

Now a real MCP client starts each server as a subprocess and talks to it. No model and no API key are involved. This is the core of client_check.py:

async with Client(StdioServerParameters(command=command, args=args, cwd=cwd)) as client:
    print(f"{label} server: {client.server_info.name}")
    for t in (await client.list_tools()).tools:
        print(f"tool      {t.name} {sorted(t.input_schema['properties'])}")
    for r in (await client.list_resources()).resources:
        print(f"resource  {r.uri}")
    for p in (await client.list_prompts()).prompts:
        print(f"prompt    {p.name} {[a.name for a in p.arguments]}")
    first = (await client.list_tools()).tools[0]
    claude_tool = {"name": first.name, "description": first.description, "input_schema": first.input_schema}
    print("for Claude     ->", sorted(claude_tool))
    done = await client.call_tool("order_status", {"order_id": "A-1001"})
    print("call tool      ->", done.content[0].text)
    read = await client.read_resource("policy://returns")
    print("read resource  ->", read.contents[0].text)
    got = await client.get_prompt("ticket_summary", {"ticket_id": "T-204"})
    print("get prompt     ->", got.messages[0].content.text)

run_all.py checks the Python server, then the TypeScript server, with the very same client:

python server: supportdesk
tool      order_status ['order_id']
resource  policy://returns
prompt    ticket_summary ['ticket_id']
for Claude     -> ['description', 'input_schema', 'name']
call tool      -> shipped, arrives Friday
read resource  -> Returns are accepted for 30 days if the item is unused.
get prompt     -> Summarise T-204.

typescript server: supportdesk
tool      order_status ['order_id']
resource  policy://returns
prompt    ticket_summary ['ticket_id']
for Claude     -> ['description', 'input_schema', 'name']
call tool      -> shipped, arrives Friday
read resource  -> Returns are accepted for 30 days if the item is unused.
get prompt     -> Summarise T-204.

The two blocks are identical. To the client, it is the same server. And the for Claude line shows the three fields ready to hand to Claude as a tool.

Which of the three fits the job

Say a team wants every app to look up orders and to read the returns policy. Three tempting answers fail:

  • Paste the policy into every prompt. The copies go stale, and every request carries the extra text.
  • Write a connector inside each app. The same work, again and again.
  • Make everything a tool. The model then has to call a tool just to read text.

The answer is one MCP server. The lookup is a tool, because it does something. The policy is a resource, because it is content to read. A request the user starts from, like "summarise this ticket", is a prompt.

The same rule covers a catalog. If an agent keeps calling a "list SKUs" tool before every answer just to learn what exists, expose that list as a resource it reads once. Exploratory tool calls go away, and nothing gets pasted into system prompts.

Rule of thumb: do something, a tool. Read content, a resource. A ready-made request, a prompt.

Common mistakes

  • A vague docstring. It becomes the tool description Claude reads, so "gets stock" on two tools makes the model guess.
  • Reading content through a tool. Fixed text belongs in a resource the app can attach.
  • Hiding a write in a resource. Resources are for reading. An action that changes data is a tool, and an approval step in the client goes in front of it.
  • Writing glue per app. If three apps need the same data, that is the signal for one server.

Recap

IdeaIn practice
Server declares, client asksList first, then use: the same calls work for any server
ToolThe model calls it; name, docstring and typed args become the tool definition
ResourceThe app reads it by URI
PromptThe user picks it and fills in the arguments
stdioThe client starts the server as a local process

Try it yourself: add a second resource, policy://shipping, to both servers and check that the client lists it on both. The server files and the client are in the community, free to join.

Keep going in AI Engineering · 47 of 89

Previous
Custom Agent Loops and Harnesses: A Dispatch Table, an Approval Hold, Error Results and a Turn Budget
Next post
MCP Transports: stdio or Streamable HTTP, and Who Starts the Server
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

Claude Certified Developer - Foundations (CCDV-F) Exam Prep

Build and ship Claude apps: the API, agents, tools and MCP, prompts, evals, security and model choice.View on Udemy ↗: Claude Certified Developer - Foundations (CCDV-F) Exam Prep (paid course, opens in a new tab)

Related posts

Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It

A support agent forgets the customer's name, order and contact choice after twenty turns and fails 0 of 4 checks. Measure the window, clear old tool output, compact old turns and keep a notes file, and the same chat passes 4 of 4 with 470 tokens instead of 2,945.

What LangChain Is For, and When to Skip It: Five Standard Parts, One Pipe, and a Decision Table

LangChain is a box of standard parts (models, prompts, retrievers, tools, parsers) that snap together with a pipe. The same refund question through the plain Anthropic SDK (1 import, 13 lines) and a chain (3 imports, 14 lines) gives the same answer word for word. It pays off when the bot grows; for one call, the SDK is simpler, with 16 packages instead of 38.

Why Chains Break: No Branch, No Retry, No Pause, and the Same Refund Assistant as a LangGraph Graph

A refund assistant built three ways. The chain runs classify, retrieve, reply once: it answers an opening-hours question with the billing line, misses the 30-day window, and sends a $150 refund with approved False. Plain if/while fixes it but hides the flow; a LangGraph StateGraph puts the branch, the retry loop and the approval stop in the arrows.

LangGraph Nodes, Edges and State: Build Your First Graph, Route With a Conditional Edge, and Read the Run Three Ways

Two small graphs. A refund skeleton: SupportState, a classify node, a route function on a conditional edge, and an Annotated log that appends instead of overwriting. A help desk: classify and answer call a scripted test model, spam goes straight to END after one model call instead of two, and the same run read with invoke, stream values and stream updates.

On this page

  • Where the server sits
  • Three kinds of things, three controllers
  • server.py: the whole server
  • The code writes the tool definition
  • server.ts: the same server in TypeScript
  • A client lists, then uses
  • Which of the three fits the job
  • Common mistakes
  • Recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

Claude Certified Developer - Foundations (CCDV-F) Exam Prep

Build and ship Claude apps: the API, agents, tools and MCP, prompts, evals, security and model choice.View on Udemy ↗: Claude Certified Developer - Foundations (CCDV-F) Exam Prep (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.