Building and deploying a Python MCP server with FastMCP and CircleCI
Full Stack Engineer
Extending Large Language Models (LLMs) with custom tools has become increasingly valuable in today’s AI landscape. Model Context Protocol (MCP) servers provide a standardized way to connect external tools and resources to LLMs. This can enhance their capabilities beyond basic text generation.
While thousands of pre-built MCP servers exist, creating your own allows you to address specific workflows. You can implement use cases that off-the-shelf solutions cannot handle. This is where the real power lies.
In this tutorial, you will learn to build a document parsing server that enables MCP hosts to understand various file formats. You will use FastMCP, the standard framework for building MCP servers in Python. You will also bundle your application into a Python package and publish on PyPI using an automated CI/CD pipeline.
By the end, you will have a fully functional document reader MCP server that extracts text from various document formats.
Here is a demo of what you will build.
Prerequisites
Before diving in, make sure you have:
- Python 3.12 or newer installed on your system
- Node.js 22 or 24 for running the MCP Inspector
- Basic understanding of Python packaging concepts
- A PyPI account for publishing your package
- A GitHub account for version control
- A CircleCI account connected to your GitHub account for creating CI/CD pipelines
- Claude Desktop for using your MCP server
Setting up the development environment
Building an MCP server opens up exciting possibilities for extending LLM capabilities with custom tools and resources. FastMCP simplifies this process with a clean API using decorators that handle server protocol complexities.
You can visit this GitHub repository to explore the code for the server you are about to build.
Initializing the project directory
First, create a new directory for our project and set up the basic structure:
mkdir document-brain
cd document-brain
Installing UV
For dependency management, you will use uv, a fast package and project manager for Python. On macOS and Linux, install it with the official installer:
curl -LsSf https://astral.sh/uv/install.sh | sh
On Windows, open PowerShell and run:
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
You can also install uv with Homebrew (brew install uv) or with pipx install uv.
Restart your terminal completely. Then verify the installation:
uv --version
Now initialize your project with uv:
uv init
This command automatically creates:
.python-version: Ensures consistent Python versions across environments.gitignore: Lists files and directories for Git to ignore.src/document_brain/__init__.py: A Python package with amain()function, a starting point for development.pyproject.toml: Defines project metadata, dependencies, and a build system.README.md: An overview of the project’s purpose, usage instructions, and other relevant information.
These files collectively set up a foundational structure for a Python project. This facilitates development and collaboration.
Creating a virtual environment and installing dependencies
When installing packages and dependencies, uv automatically creates a virtual environment name .venv.
Install the necessary packages for developing and testing your MCP server. Run:
uv add fastmcp "markitdown[all]"
uv add --dev pytest
These packages provide:
- FastMCP, with a command-line interface for running, debugging, and installing your server
- Markitdown for document parsing functionality
- Testing (pytest)
You don’t need separate packages for building and publishing. uv handles both.
uv init already created the src/document_brain/ package. Create a file for your MCP server:
touch src/document_brain/server.py
Your project structure looks like this:
project_root/
├── src/
│ └── document_brain/
│ ├── __init__.py # Initializes server
│ └── server.py # Contains the 'mcp' instance and definitions
├── tests/
│ ├── __init__.py # Makes tests discoverable
│ └── test_server.py # Tests for your MCP server
├── pyproject.toml # Project configuration
├── uv.lock # Locked dependency versions
└── README.md # Project documentation
This structure follows the recommended Python packaging standards with src-layout. The approach prevents import issues during development.
Building the MCP Server with FastMCP
In this part, you will begin by understanding three primary components of MCP servers (tools, resources, and prompts).
Understanding the core components
MCP servers consists of three key components:
- Tools: Model-controlled functions that LLMs can call to perform actions or interact with external systems.
- Resources: Application-controlled data sources that inject contextual information from your systems into the conversation.
- Prompts: User-controlled templates that can be invoked through UI elements to help users interact with the LLM in structured ways.
Now, implement your document brain server in src/document_brain/server.py:
from fastmcp import FastMCP
from fastmcp.prompts import Message
from fastmcp.resources import DirectoryResource
from pathlib import Path
import os
from markitdown import MarkItDown
md = MarkItDown()
# Initialize the FastMCP server
mcp = FastMCP("DocumentBrain")
@mcp.tool(
annotations={
"title": "Read Any Document",
"readOnlyHint": True,
"openWorldHint": False
}
)
def read_any_document(file_path: str) -> str:
"""Read any supported document and return its text content, including OCR for images.
Args:
file_path: Path to the document to process.
Returns:
Extracted text content as a string.
"""
try:
expanded_path = os.path.expanduser(file_path)
return md.convert(expanded_path).text_content
except Exception as e:
return f"Error reading file: {str(e)}"
@mcp.tool(
annotations={
"title": "Save File to PC",
"readOnlyHint": False,
"openWorldHint": False
}
)
def save_file_to_pc(filepath: str, content: str) -> str:
"""
Save content to a file on your computer.
Args:
filepath: Path of the file to save, for example ~/Desktop/summary.md
content: Content to write to the file
Returns:
A success or error message
"""
try:
# Expand ~ to the user's home directory
full_path = os.path.expanduser(filepath)
# Ensure the parent directory exists
os.makedirs(os.path.dirname(full_path) or ".", exist_ok=True)
# Write the content to the file
with open(full_path, 'w', encoding='utf-8') as f:
f.write(content)
return f"File successfully saved to {full_path}"
except Exception as e:
return f"Error saving file: {str(e)}"
# Now add a resource
# Define the path to the current directory
documents_path = Path(".").resolve()
# Create a DirectoryResource to list files in the current directory
documents_resource = DirectoryResource(
uri="docs://files",
path=documents_path,
name="Local Document Directory",
description="Lists all files in the current working directory.",
recursive=False # Set to True if you want to include subdirectories
)
# Add the resource to your FastMCP server
mcp.add_resource(documents_resource)
@mcp.resource("docs://file/{filename}")
def get_document_content(filename: str) -> str:
"""Retrieve the content of a specified document."""
try:
file_path = documents_path / filename
if not file_path.exists():
return f"File not found: {filename}"
return md.convert(str(file_path)).text_content
except Exception as e:
return f"Error reading file {filename}: {str(e)}"
# Prompt: Analyze document data
@mcp.prompt()
def analyze_data(text: str) -> list[Message]:
"""Prompt to analyze the data in the provided document text.
Args:
text: The content of the document to be analyzed.
Returns:
A list of messages guiding the LLM to analyze the data.
"""
return [
Message(
"Assume the role of a data analyst specializing in academic research. "
"Your task is to critically analyze the data presented in the attached academic document. "
"Start by summarizing the key data points and notable findings. "
f"Identify any patterns, trends, correlations, or anomalies within the dataset:\n\n{text}"
)
]
def main():
"""Entry point for the MCP server."""
mcp.run()
if __name__ == "__main__":
main()
Here is a breakdown what you’ve created:
- Tools: Two functions decorated with
@mcp.tool(). Theread_any_documenttool extracts text from documents, andsave_file_to_pcsaves content to a file on your computer. - Resources: A dynamic resource that provides access to documents in the current directory and a function to retrieve document content.
- Prompts: A prompt that users can invoke to analyze document content.
- Main function: The
main()function serves as an entry point for running the server.
If you’ve built MCP servers with from mcp.server.fastmcp import FastMCP, version 2 of the MCP Python SDK removed that module. Import FastMCP from the standalone fastmcp package instead, as this server does.
Now, update the src/document_brain/__init__.py file to expose server components:
"""Document Reader MCP server for extracting text from various document formats."""
from .server import mcp, read_any_document, main
Testing the MCP Server
In this part you will run your server and test what it can do. You’ll run each command with uv run, which uses the project’s virtual environment without activating it.
Now proceed to test the MCP server using MCP inspector. Make sure you are connected to the internet.
Manual testing with the MCP Inspector
FastMCP can launch the MCP Inspector, a browser-based tool for testing MCP servers. The Inspector runs with npx, so it needs Node.js. To test your server:
uv run fastmcp dev inspector src/document_brain/server.py
This starts the server and opens the Inspector in your browser (typically at http://127.0.0.1:6274). Turn on the switch on the server card (the Inspector lists it as fastmcp) to connect, then explore the Tools, Prompts, and Resources tabs to test your implementation.
You can verify that your server is running.
In the Tools tab, there are two tools:
read_any_documentsave_file_to_pc.
You can click on any tool and test it. For example, clicking on the read_any_document tool will show an input field for the file path. Enter the full path to any supported file (such as Excel) on your machine. Click Execute Tool and the tool will convert the Excel file to markdown, displaying the extracted text content.
You can also test your MCP Server in Claude Desktop by running:
uv run fastmcp install claude-desktop src/document_brain/server.py --project .
The --project . option tells Claude Desktop to run the server in your project’s environment, so the server can import MarkItDown. Restart Claude Desktop completely and the MCP server will be attached.
Now ask Claude to analyze data in an Excel file global_inflation_data.xlsx, saved locally. Name the tool in your prompt. Otherwise, Claude Desktop may offer to use its own file access instead of your server. For example: “Use the read_any_document tool from DocumentBrain to analyze the data in ~/document-brain/global_inflation_data.xlsx”. Replace the path with the location of your Excel file.
Before Claude calls your tool, it asks for permission. Select Allow once.
Claude reads the file through your server and analyzes the data.
Your MCP Server is fully operational in Claude Desktop.
Testing the server with the MCP Inspector CLI
The MCP Inspector also has a command-line mode. It connects to your server, sends one MCP request, prints the result, and exits. It doesn’t need a browser, so you can use it in scripts and CI pipelines.
List the tools your server exposes:
npx @modelcontextprotocol/inspector --cli uv run fastmcp run src/document_brain/server.py --method tools/list
Call a tool by name, passing its arguments as JSON:
npx @modelcontextprotocol/inspector --cli uv run fastmcp run src/document_brain/server.py \
--method tools/call --tool-name read_any_document \
--tool-args-json '{"file_path": "pyproject.toml"}'
The response contains the text of pyproject.toml. Add --format json to get output that you can check with a tool like jq. The CLI also exits with a non-zero status when it can’t reach the server or a tool call fails. Later in this tutorial, your CircleCI pipeline uses these commands to check the server on every push.
Setting up automated testing
To set up a simple test for our MCP server, create a test directory:
mkdir -p tests
touch tests/test_server.py
touch tests/__init__.py
Now, add basic tests in tests/test_server.py:
import pytest
from document_brain.server import read_any_document
# Fixture to create a temporary text file
@pytest.fixture
def temp_text_file(tmp_path):
file_path = tmp_path / "test_document.txt"
file_path.write_text("This is a test document.")
return file_path
# Test reading a valid text file
def test_read_valid_document(temp_text_file):
content = read_any_document(str(temp_text_file))
assert "This is a test document." in content
# Test reading a non-existent file
def test_read_nonexistent_file():
content = read_any_document("nonexistent_file.txt")
assert "Error reading file" in content
These tests verify that our document reader functions work correctly. Run the tests:
uv run pytest tests/ -v
The -v flag tells pytest to output detailed logs about the tests.
Packaging the Python project
To prepare your application for distribution, configure the metadata in pyproject.toml:
[build-system]
requires = ["setuptools>=77.0"]
build-backend = "setuptools.build_meta"
[project]
name = "mcp-document-brain-<your-username>"
version = "0.1.1"
description = "MCP server for converting files to markdown using Markitdown"
readme = "README.md"
authors = [
{name = "Your name", email = "example.email@domain.com"}
]
license = "MIT"
classifiers = [
"Programming Language :: Python :: 3",
"Operating System :: OS Independent",
]
requires-python = ">=3.12"
dependencies = [
"fastmcp>=4.2,<5",
"markitdown[all]>=0.1.9",
]
[dependency-groups]
dev = [
"pytest>=9.2",
]
[project.scripts]
mcp-document-brain = "document_brain.server:main"
[tool.setuptools]
package-dir = {"" = "src"}
[tool.pytest.ini_options]
testpaths = ["tests"]
This configuration:
- Sets up basic package metadata
- Declares dependencies
- Creates a command-line entry point
- Configures our development tools
Package names on PyPI are global, and mcp-document-brain is already taken. Replace <your-username> with your PyPI username or another unique suffix. The companion repository publishes as mcp-document-brain-circlci.
Because you changed pyproject.toml, update the lockfile:
uv lock
Commit uv.lock with your code. Your CircleCI pipeline installs the exact versions it lists.
Now, add some documentation in README.md to provide users with more details about your package.
Build your package with uv:
uv build
This generates distribution files in the dist/ directory.
Publishing your package to PyPI
Before uploading your package to PyPI (the Python Package Index), you will need to complete a few important steps:
- Create a PyPI account if you don’t have one already:
- Go to the PyPI registration page
- Verify your email address after registering
- Set up two-factor authentication (2FA) for better security
- Generate an API token instead of using your password:
- Log in to your PyPI account
- Go to Account Settings → API tokens
- Click “Add API token”, give it a name (like “document-brain-upload”), and create it
- Save the token somewhere safe - you will need it later on in the tutorial.
-
Upload your package with
uv. It reads your token from theUV_PUBLISH_TOKENenvironment variable:export UV_PUBLISH_TOKEN="pypi-...your-token-here..." uv publish
To try a release without touching the real index first, create an account and an API token on TestPyPI. Then run uv publish --publish-url https://test.pypi.org/legacy/ with your TestPyPI token.
Once your package is published, anyone can install it with:
pip install mcp-document-brain-<your-username>
# Or using uv
uv add mcp-document-brain-<your-username>
Run it directly:
mcp-document-brain
The server starts and waits for an MCP client to connect over standard input. Press Ctrl+C to stop it.
You can view your published package at https://pypi.org/project/mcp-document-brain-<your-username>/
Troubleshooting tips
- If you get an error about the package name being taken, choose a different name in your
pyproject.tomlfile - If uploads fail, make sure your token has the right permissions and has not expired
- Check the PyPI help docs if you run into problems.
Automating Python package publishing with CircleCI and uv
Automating your Python package publishing flow can save you hours of manual effort and reduce human error. In this part, you will learn how to use CircleCI to automate testing, building, and publishing a Python package to PyPI.
This section walks through a complete CircleCI setup that uses the uv package manager to install dependencies, build, and publish. You will create a workflow that tests your package on every push, and publishes it only when you push a version tag. This ensures publishing of your package only when it is production-ready.
Setting up CircleCI configuration
Create a CircleCI configuration file to automate testing, building, and publishing:
mkdir -p .circleci
touch .circleci/config.yml
Before breaking it down, here is the full .circleci/config.yml:
version: 2.1
jobs:
build:
docker:
- image: cimg/python:3.14
steps:
- checkout
- run:
name: Install dependencies
command: uv sync --locked
- run:
name: Run tests
command: uv run pytest tests/ -v
- run:
name: Build package
command: uv build
- persist_to_workspace:
root: .
paths:
- dist
inspect:
docker:
- image: cimg/python:3.14-node
steps:
- checkout
- run:
name: Install dependencies
command: uv sync --locked
- run:
name: Check the tools with the MCP Inspector CLI
command: |
npx --yes @modelcontextprotocol/inspector@2.15.0 --cli \
uv run mcp-document-brain \
--method tools/list --format json > tools.json
jq -e --argjson want '["read_any_document","save_file_to_pc"]' \
'[.result.tools[].name] as $have | $want - $have | length == 0' tools.json
- run:
name: Call read_any_document with the MCP Inspector CLI
command: |
npx --yes @modelcontextprotocol/inspector@2.15.0 --cli \
uv run mcp-document-brain \
--method tools/call --tool-name read_any_document \
--tool-args-json '{"file_path": "README.md"}' --format json > read.json
jq -e '.result.content[0].text | test("MCP Document Reader")' read.json
publish:
docker:
- image: cimg/python:3.14
steps:
- checkout
- attach_workspace:
at: .
- run:
name: Publish to PyPI
command: uv publish
workflows:
build-test-publish:
jobs:
- build:
filters: pipeline.git.branch or (pipeline.git.tag matches /^v.*/)
- inspect:
filters: pipeline.git.branch or (pipeline.git.tag matches /^v.*/)
- publish:
requires:
- build
- inspect
filters: pipeline.git.tag matches /^v.*/
Understanding the CircleCI configuration
This setup creates three jobs:
buildjob
This is where you define tasks before a release:
- Docker image: Uses CircleCI’s official
cimg/python:3.14image. CircleCI’s Python images includeuv, so the job doesn’t need a step to install it. - Install dependencies:
uv sync --locked
This command installs the exact versions listed in uv.lock, including your dev dependencies. The --locked flag fails the job if uv.lock is out of date with pyproject.toml.
- Run tests: Executes your test suite with
uv run pytest. You usepytestto run all tests inside thetests/folder and print verbose output. - Build the package: Uses
uv buildto generate thedist/folder, which includes.tar.gzand.whlfiles for your package. - Persist the build artifacts: These are saved to a “workspace”, a temporary shared storage between jobs.
inspect
This job checks the server the way an MCP client sees it, using the MCP Inspector CLI from earlier.
- Docker image: Uses
cimg/python:3.14-node, which adds Node.js for the Inspector. - List the tools: Starts the server through its
mcp-document-brainentry point and runstools/list. Thejqcommand fails the job ifread_any_documentorsave_file_to_pcis missing. - Call a tool: Calls
read_any_documenton the repository’sREADME.mdand checks that the response contains the README’s text.
The job pins the Inspector version (@2.15.0), so the same commit always runs against the same Inspector. The --yes flag stops npx from waiting for confirmation before it installs the Inspector.
publish
This job picks up where build and inspect left off.
- Attach the workspace: Brings the previously built
dist/folder into this job. - Upload to PyPI: The actual publishing step happens here with:
uv publish
uv publish uploads everything in dist/, using the token in the UV_PUBLISH_TOKEN environment variable. You need to store that token as an environment variable in your CircleCI project settings.
workflows: CI/CD logic
This block defines when and how your jobs run.
workflows:
build-test-publish:
jobs:
- build:
filters: pipeline.git.branch or (pipeline.git.tag matches /^v.*/)
- inspect:
filters: pipeline.git.branch or (pipeline.git.tag matches /^v.*/)
- publish:
requires:
- build
- inspect
filters: pipeline.git.tag matches /^v.*/
Here is what it means:
- The
buildandinspectjobs run on every branch, and on tags that start withv. - The
publishjob only runs afterbuildandinspectcomplete successfully. - It only runs for tags that start with
v, such asv0.1.1.
CircleCI doesn’t run workflows for tags unless the jobs have tag filters, so build and inspect need a tag filter too. This design ensures you do not accidentally publish from feature branches, from a merge to main, or from failed builds.
Managing secrets in CircleCI
To securely publish to PyPI, add your PyPI API token to your CircleCI project as an environment variable named UV_PUBLISH_TOKEN. In the CircleCI web app, open your project and select Project Settings. Select Environment Variables, then Add Variable.
You can also set the variable from your repository with the CircleCI CLI:
circleci envvar set UV_PUBLISH_TOKEN "pypi-...your-token-here..."
Publishing to PyPI
In this section, you will trigger the build, inspect, and publish jobs.
Automating the publishing process
With your CircleCI configuration in place, you will trigger deployment as follows:
- Make changes to your code and commit them
- Push to GitHub
- Create a new project in CircleCI and link your repository
- When you are ready to release, create and push a tag that starts with “v” (for example,
v0.1.1) - CircleCI tests, checks, builds, and publishes your package to PyPI
The build, inspect, and publish jobs should run successfully.
Versioning strategy
For versioning, follow Semantic Versioning:
- MAJOR version for incompatible API changes
- MINOR version for backwards-compatible functionality
- PATCH version for backwards-compatible bug fixes
To release a new version:
- Update the version in
pyproject.toml - Run
uv lockto update the lockfile - Commit the change
- Create and push a tag:
git tag v0.1.1 git push origin v0.1.1
Verifying the deployment
After the CI pipeline completes, verify your package by visiting its page on PyPI, at https://pypi.org/project/mcp-document-brain-<your-username>/.
You can also test the installation:
# Create a new virtual environment
python -m venv test_env
source test_env/bin/activate # On Windows: test_env\Scripts\activate
# Install your package from PyPI
pip install mcp-document-brain-<your-username>
# Check that the server starts and lists its tools
npx @modelcontextprotocol/inspector --cli mcp-document-brain --method tools/list
For a thorough test, create sample documents and try using your MCP server with an LLM platform that supports the MCP.
Conclusion
Congratulations! You have built a complete MCP server that extends LLM capabilities with document processing tools. You have packaged it for distribution and set up an automated CI/CD pipeline for publishing on PyPI using CircleCI.
This knowledge provides a foundation for creating more sophisticated MCP servers that could:
- Connect to databases or APIs
- Process specialized data formats
- Integrate with external services
- Execute domain-specific algorithms
MCP opens up exciting possibilities for extending LLM capabilities in standardized ways. By combining Python’s flexibility, FastMCP’s developer-friendly API, and CircleCI’s automation, you can build powerful AI-powered tools tailored to specific workflows.
Why does this matter? As AI becomes increasingly integrated into our workflows, the ability to extend LLMs with custom capabilities will be a crucial differentiator. Your custom MCP servers can provide unique value that generic AI solutions simply cannot match.
Ready to take your MCP development skills further? Sign up for CircleCI today and join the growing ecosystem of AI tool developers!