MCP : From Function Calling to Your Own Expense Tracker Server
A practical guide to the Model Context Protocol, and how to build a personal MCP server you can later share with everyone. Introduction: The USB-C Moment for AI Large language models are brilliant at reasoning, but on t
A practical guide to the Model Context Protocol, and how to build a personal MCP server you can later share with everyone.
Introduction: The USB-C Moment for AI
Large language models are brilliant at reasoning, but on their own they are sealed boxes. They cannot read your files, check your calendar, query your database or post to Slack. For years, every team that wanted to connect an AI to real-world systems wrote its own glue code, and every integration was a one-off.
The Model Context Protocol (MCP) changes that. It is an open standard that defines how AI applications talk to external tools and data sources. Think of it as USB-C for AI: build a connector once, and any compliant AI app can plug into it.
In this article we will cover why MCP exists, how it works under the hood (architecture, data layer, transport layer, lifecycle, error handling), and then put it to work by building a personal Expense Tracker MCP server that runs locally today and can be turned into a remote server tomorrow.
- What Is Context? Context is everything an AI can "see" when it generates a response. More formally, context is the information (conversation history, external documents, tool results and so on) that the LLM uses to produce its output.
An LLM with poor context guesses. An LLM with rich, relevant, live context acts. The central question of modern AI engineering is therefore: how do we get the right context to the model, reliably and safely?
- The Road to MCP Function calling: the first answer In mid-2023, OpenAI introduced function calling: a way for LLMs to call external functions. The idea is simple. You describe a function to the model, the model decides when it is needed and emits structured arguments, and your code executes it.
For example, given the request "Read the content of the file abc.txt", the model responds with a structured call such as load_file(name="abc.txt"), and your application runs the real function and feeds the result back.
The rise of tools
Once models could call functions, tools multiplied: a weather API, a database, GitHub, Slack, Google Drive. But there was a catch. Each tool was wired to each AI application in its own bespoke way. With N applications and M tools you ended up maintaining something close to N Γ M custom integrations.
Function calling vs MCP
A good way to see the difference is to look at where the code lives.
Plain function/tool calling: the function definition (for example get_weather(city: str)) and the server endpoint that serves it (for example a /weather route in a web framework) are both part of your application. The client, the server and the glue are all yours to build, secure and maintain.
MCP: the tool lives in a standalone MCP server, and any MCP client speaks to it using a shared protocol. The AI app does not need to know how the tool is implemented, only how to talk MCP.
Function calling is the mechanism by which a model requests an action. MCP is the standard that governs how those tools are described, discovered and invoked across applications.
- Why MCP? The Ecosystem Effect MCP is an open standard, and its value compounds as more people adopt it:
More AI chatbots supporting MCP means more incentive for services to build MCP servers.
More MCP servers available means more tools, and therefore more value, for the AI.
More adoption leads to more standardization, which leads to more ecosystem value.
Not supporting MCP increasingly means being cut off from a rapidly growing ecosystem.
This is a classic network effect, and it is why MCP has moved so quickly from a specification to an industry-wide convention.
- MCP Architecture MCP follows a client-server model with three roles:
Host: the AI application the user interacts with (a chat app, an IDE, a desktop assistant). It coordinates everything.
Client: a connector component created by the host. Each client maintains a dedicated one-to-one connection with a single server.
Server: a program that exposes capabilities to the host.
A host can run several clients at once. For example, one client might talk to a local filesystem server while another talks to a remote GitHub server.
The three primitives
Servers offer capabilities to the host through primitives, the things a server can offer:
Tools: executable actions the model can invoke (add an expense, create an issue).
Resources: read-only data the host can pull in as context (a file, a database record).
Prompts: reusable prompt templates that guide how a task is performed.
Benefits of the design
Decoupling. Because the AI app and the tool are separate processes, you get safety (the model never touches your systems directly; the server decides what is exposed) and parallelism (many servers can work at the same time).
Scalability. Adding a new capability means adding a new server, not rewriting your application.
- The Data Layer: JSON-RPC 2.0 MCP is split into two layers. The data layer is the language and grammar everyone agrees upon. The transport layer is how those messages physically travel.
The data layer is built on JSON-RPC 2.0, which combines two ideas:
RPC (Remote Procedure Call): lets a program execute a function on another machine as if it were local, hiding the details of network communication and data transfer.
JSON: a simple, human-readable, universally supported format.
Together, they let developers structure requests and responses in a standardized JSON shape.
Request and response
Minimize image
Edit image
Delete image
Add a caption (optional)
Requests need a response. Notifications are messages without an id; they are fire-and-forget and do not expect a reply. Notifications can flow in either direction, including server to client.
Why JSON-RPC instead of REST?
REST communicates over HTTP, and behind the scenes many headers and a lot of metadata travel with every request. That overhead is heavy for a conversation that is really just "call this function, give me the result". Debugging is harder when something fails, extra data makes transfers slower and costlier, and the interaction is fundamentally one-way (client asks, server answers).
JSON-RPC fits MCP better because it is:
Lightweight, with minimal envelope overhead.
Bi-directional, so servers can also send requests and notifications to clients.
Transport-agnostic, so it works over HTTP, stdio, WebSockets or even a custom transport you write yourself.
Batch-capable and notification-capable out of the box.
- The Transport Layer The transport layer is the mechanism that moves JSON-RPC messages between client and server. The right choice depends on where the server runs.
Local server: a program running on your own computer. Uses stdio.
Remote server: a program running on another machine somewhere on the network or internet, reached over a network. Uses HTTP (with streaming).
Local: stdio
stdio refers to the built-in streams every program has: stdin (input the program reads) and stdout (output the program writes). MCP reuses them as the transport:
The host launches the server as a subprocess on the same machine.
The client writes JSON-RPC messages into the server's stdin.
The server reads them, processes them and writes the response to its stdout.
It is fast, simple and secure, since communication never leaves your machine. One practical rule follows from this: in a stdio server, never print debug text to stdout, because it would corrupt the protocol stream. Log to stderr instead.
Remote: HTTP with streaming
HTTP lets the host reach servers running anywhere. The client sends JSON-RPC requests as HTTP POSTs with a JSON payload. For streaming, MCP uses SSE (Server-Sent Events), an extension of HTTP in which the server keeps one connection open and pushes multiple messages as they become ready. This is ideal for long-running tasks or incremental updates.
Note: the MCP specification has since evolved this remote design into a transport called Streamable HTTP, which supersedes the original standalone HTTP+SSE transport while keeping the same idea: JSON-RPC over HTTP, with optional streaming. When you build a new remote server today, use your SDK's HTTP (Streamable HTTP) option.
- The MCP Lifecycle The lifecycle describes the complete sequence of steps that govern how a host (client) and a server establish, use and end a session. It has three phases.
Phase 1: Initialization
This must be the very first interaction between client and server. It does two things:
Protocol version negotiation: both sides agree on a compatible version.
Capability negotiation: both sides declare which features they support for the session.
Client capabilities include roots (which parts of the filesystem the server may look at), sampling (the server asks the client's model to generate text) and elicitation (the server asks the user for missing information mid-task).
Server capabilities include prompts, resources, tools and logging. Some carry sub-capabilities, such as listChanged (the server will notify you when its list of tools or resources changes) and subscribe (the client can subscribe to updates on a specific resource).
Phase 2: Operation
The client and server exchange messages according to the negotiated capabilities, respecting the agreed protocol version. This is where tools are listed, called and answered.
Phase 3: Shutdown
One side, typically the client, initiates shutdown. Interestingly, no special JSON-RPC shutdown message exists; the transport layer is responsible for signaling termination (closing stdin for stdio, closing the connection for HTTP).
Special case: ping
ping is a lightweight request/response method defined in MCP. Its purpose is to check whether the other side (host or server) is still alive and the connection is responsive.
- Error Handling Error handling is how the client and server signal that something went wrong with a request. MCP inherits JSON-RPC's standard error object (a code, a message and optional data).
Common causes of errors:
A timeout is exceeded and the client cancels the request.
An internal server failure occurs during processing.
Invalid arguments are passed to a tool.
Standard JSON-RPC error codes:
-32700: Parse error (the JSON was malformed)
-32600: Invalid request
-32601: Method not found
-32602: Invalid params
-32603: Internal error
-32000 to -32099: reserved for server-defined errors
- Connectors vs Custom Servers A connector is a built-in feature that links Claude to MCP servers automatically, with no manual setup or configuration. Connectors are curated and managed: they are built, hosted and maintained by the provider, and they come with OAuth login flows, managed security, rate limits and stability guarantees.
So why not use connectors for everything? Because curated connectors only cover popular services. If you need something personal, niche or private, such as your own expense data, you build your own MCP server. And since MCP is an open standard, you are free to do exactly that.
- Hands-On: Build Your Own Expense Tracker MCP Server Let us put everything together. The goal: tell your AI assistant "I spent 450 on groceries today" and have it recorded; later ask "How much did I spend on food this month?" and get a real answer from your own data.
Tooling
Two libraries are commonly used to build servers in Python:
The official MCP SDK: the reference implementation of the protocol, a set of rules for hosts and servers.
FastMCP: a higher-level framework that makes defining servers as simple as decorating Python functions.
We will use FastMCP plus SQLite (built into Python), so there is no database server to install.
Minimize image
Edit image
Delete image
Add a caption (optional)
The server (server.py)
Minimize image
Edit image
Delete image
Add a caption (optional)
Notice how the three MCP primitives map directly onto the code: @mcp.tool() for tools, @mcp.resource() for resources and @mcp.prompt() for prompts. FastMCP also generates each tool's JSON schema from your type hints and docstrings, which is what the model reads to decide when and how to call it.
Minimize image
Edit image
Delete image
Add a caption (optional)
Connect it to Claude Desktop (local, stdio)
Add the server to Claude Desktop's configuration file (Settings, then Developer, then Edit Config):
Minimize image
Edit image
Delete image
Add a caption (optional)
Restart Claude Desktop. Behind the scenes, the lifecycle we studied plays out: the host launches your script as a subprocess, the client sends an initialize request, both sides negotiate capabilities, and then Claude can list and call your tools through JSON-RPC over stdin and stdout.
Try it:
"Add an expense: 450 on groceries today."
"Show everything I spent this week."
"Summarize my spending by category for November."
Your data stays in a single expenses.db file on your own machine. For a personal tool, that is a feature.
- Next Step: Make It Remote A local server is perfect for one person on one computer. To use your tracker from your phone, on the web, or to share it with others, it needs to become a remote server. Conveniently, the architecture makes this a small change, because only the transport layer differs. Your tools stay exactly the same.
Minimize image
Edit image
Delete image
Add a caption (optional)
Step 2: Host it
Deploy the server to any platform that can run a Python web process, such as a cloud VM, a container platform or a managed MCP hosting service. Put it behind HTTPS; remote MCP endpoints should never be exposed over plain HTTP.
Step 3: Add it as a connector in Claude
In Claude, open Settings, then Connectors, and add a custom connector using your server's URL. Once connected, your expense tools appear in Claude on the web and, depending on your plan and platform, on mobile as well.
Step 4: Harden it before sharing
This is the step that separates a demo from a product. A local stdio server inherits the safety of your machine; a remote server inherits the risks of the internet.
Authentication: require OAuth (or at minimum a token) so that only authorized users can call your tools. MCP's remote design supports OAuth-based authorization.
Per-user data isolation: the single expenses.db above is fine for one person. For many users, add a user_id column (or a separate database per user) and derive it from the authenticated identity, never from a tool argument the model can fill in.
A real database: move from SQLite to a managed database such as Postgres when you have concurrent users.
Rate limiting, input validation and logging: treat every tool argument as untrusted input.
Least privilege: expose only the tools users need. Consider whether destructive actions (such as delete) need explicit confirmation.
The roadmap
Today: local stdio server, personal data, Claude Desktop.
Next: remote HTTP server with authentication, reachable from anywhere.
Then: a shared connector that anyone can add to their Claude, with per-user accounts and isolated data.
Conclusion
MCP takes the idea behind function calling and turns it into a standard: a clean separation between hosts, clients and servers; a lightweight JSON-RPC 2.0 data layer; flexible transports for local and remote use; and a well-defined lifecycle with capability negotiation and standard error handling.
The best way to understand a protocol is to build with it. In under 100 lines of Python, you now have an AI-accessible expense tracker, and a clear path from "works on my laptop" to "works for everyone."
The ecosystem is growing fast, and every server you build makes it a little more valuable. What will you connect next?
Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.