MCP-ify Your Library: Open Up an Entire SDK to AI Agents
Turn a Python library into an MCP server with AWS Transform: every function becomes an agent-callable tool, with a validated MCP test suite.
A 5-function Python string utility library. One ATX command. A custom transformation definition. The result: an MCP server that exposes every function as a tool any AI agent can call, with the original tests still passing and a generated MCP test suite that ATX validates and self-corrects. Cost is a few dollars or less in agent-minutes, depending on the run (see the cost note below).
The Model Context Protocol: Why It Matters
AI coding assistants are only as useful as the tools they can reach. Without tool access, an agent can write code that calls your library, but it cannot call your library directly. It cannot test a slugify function, extract emails from sample text, or verify that a camelCase converter handles edge cases. It can only generate code and hope it works.
The Model Context Protocol (MCP) changes this. MCP is an open standard that defines how AI agents discover, connect to, and invoke tools over a structured interface. An MCP server exposes functions as typed tools with parameter schemas and descriptions. An MCP client (Kiro, Claude Code, Amazon Q Developer, Cursor, or any compatible tool) connects to that server and gains the ability to call those functions directly during a conversation.
The protocol uses JSON-RPC over stdio or HTTP. Each tool declares its name, description, and input schema. When an agent needs to call a tool, it sends a
call_tool request with the tool name and arguments. The server executes the function and returns the result. No glue code. No REST endpoints. No authentication setup for local use.This matters because it bridges the gap between "library you import in code" and "capability an AI agent can use interactively." Every Python library, every utility module, every internal SDK becomes a potential MCP server. The barrier is mechanical: someone has to write the wrapper. That mechanical work is exactly what AWS Transform Custom eliminates.
The Starting Point: A Simple Python Library
The project is a string utility library with five functions and ten passing tests:
string-utils/├── src/│ ├── __init__.py│ └── string_utils.py ← 5 public functions├── tests/│ ├── __init__.py│ └── test_string_utils.py ← 10 tests└── pyproject.tomlThe library provides:
- slugify(text, separator) converts text to URL-friendly slugs
- truncate(text, max_length, suffix) truncates with configurable suffix
- word_count(text) counts whitespace-separated words
- extract_emails(text) extracts email addresses via regex
- camel_to_snake(text) converts camelCase/PascalCase to snake_case
All functions are pure, well-typed, and documented with docstrings. The tests cover basic behavior, edge cases (empty strings, special characters), and custom parameters:
"""Tests for string_utils module."""
from src.string_utils import slugify, truncate, word_count, extract_emails, camel_to_snake
def test_slugify_basic(): assert slugify("Hello World") == "hello-world"
def test_slugify_special_chars(): assert slugify("What's up? 100% done!") == "whats-up-100-done"
def test_slugify_custom_separator(): assert slugify("Hello World", separator="_") == "hello_world"
def test_truncate_short_text(): assert truncate("Hi", max_length=10) == "Hi"
def test_truncate_long_text(): result = truncate("This is a long sentence that needs truncating", max_length=20) assert len(result) <= 20 assert result.endswith("...")
def test_word_count(): assert word_count("one two three") == 3
def test_word_count_empty(): assert word_count("") == 0 assert word_count(" ") == 0
def test_extract_emails(): text = "Contact us at hello@example.com or support@test.org" emails = extract_emails(text) assert "hello@example.com" in emails assert "support@test.org" in emails
def test_extract_emails_none(): assert extract_emails("no emails here") == []
def test_camel_to_snake(): assert camel_to_snake("camelCase") == "camel_case" assert camel_to_snake("PascalCase") == "pascal_case" assert camel_to_snake("getHTTPResponse") == "get_http_response"This is a perfectly functional library. But it's invisible to AI agents. To use these functions, an agent would have to write Python code, import the module, and execute it in a sandbox. With MCP, the agent can call
slugify directly, get the result, and use it in conversation, all without writing and running a script.Running the Transformation

cd string-utilsgit init && git add . && git commit -m "initial: string utility library with tests"
aws configure # configure AWS credentials (or use env vars / a profile)atx> Wrap this Python library as an MCP server. Each public function should become a callable tool. Use the fastmcp package. Preserve all existing tests.ATX Found an Existing Transformation Definition
This is where ATX's registry pays off. Instead of creating a new transformation definition from scratch, ATX searched the shared registry and found an existing TD:
Found matching transformation definition: Name: project-to-mcp-server Description: Wrap a Python project's public API as an MCP server using fastmcp Lessons: 12 (from prior executions)The
project-to-mcp-server TD has already been used across multiple repos. It carries 12 lessons from prior executions, encoding learnings like "always return strings from MCP tools" and "import from the library inside the function body to avoid circular imports." ATX doesn't start from zero. It starts from the accumulated experience of every team that has run this transformation before.This is the continual learning advantage. The first team to MCP-ify a library contributed lessons. Every subsequent execution benefits from those lessons, and contributes new ones. The TD gets better with each use.
Note for readers:project-to-mcp-serveris a custom transformation definition, not an AWS-managed one. Transformation definitions are account-specific, so it won't exist in your registry until you (or a teammate) create and publish it. TheSKILL.mdfor this TD is included with this post's demo — publish it once withatx custom def publish, and then the "found an existing TD" experience above is what your teammates see. A fresh account starts by creating it.
What ATX Produced
Three files changed, 93 insertions, 1 deletion:
src/mcp_server.py | 81 +++++++++++++++++++++++++++++++++ mcp-config-snippet.json | 7 +++ pyproject.toml | 5 ++-The MCP Server: src/mcp_server.py (81 lines)
Here is the complete generated server:
"""MCP Server exposing string-utils functions as tools."""
import jsonfrom mcp.server.fastmcp import FastMCP
mcp = FastMCP("string-utils")
@mcp.tool()def slugify(text: str, separator: str = "-") -> str: """Convert text to a URL-friendly slug.""" from src.string_utils import slugify as _slugify return _slugify(text, separator)
@mcp.tool()def truncate(text: str, max_length: int = 100, suffix: str = "...") -> str: """Truncate text to a maximum length, adding a suffix if truncated.""" from src.string_utils import truncate as _truncate return _truncate(text, max_length, suffix)
@mcp.tool()def word_count(text: str) -> str: """Count the number of words in text.""" from src.string_utils import word_count as _word_count return str(_word_count(text))
@mcp.tool()def extract_emails(text: str) -> str: """Extract all email addresses from text.""" from src.string_utils import extract_emails as _extract_emails return json.dumps(_extract_emails(text))
@mcp.tool()def camel_to_snake(text: str) -> str: """Convert camelCase or PascalCase to snake_case.""" from src.string_utils import camel_to_snake as _camel_to_snake return _camel_to_snake(text)
@mcp.resource("config://project-info")def get_project_info() -> str: """Return project configuration from pyproject.toml.""" with open("pyproject.toml") as f: return f.read()
if __name__ == "__main__": mcp.run(transport="stdio")The Client Configuration: mcp-config-snippet.json
{ "mcpServers": { "string-utils": { "command": "python", "args": ["src/mcp_server.py"], "cwd": "/path/to/project" } }}The Dependency Update: pyproject.toml
ATX added
mcp>=1.0.0 to the dependencies list, ensuring the fastmcp package is available when the server runs.The Thin Wrapper Pattern
The generated server follows a deliberate architectural pattern: thin delegation. Each
@mcp.tool() function does exactly three things:- Imports the original function from the library (inside the function body)
- Delegates to it with the provided arguments
- Returns the result as a string
This pattern has several advantages that the TD's lessons encode:
No logic duplication. The MCP tools contain zero business logic. All behavior lives in
string_utils.py where it always has. If someone fixes a bug in slugify , the MCP tool automatically picks up the fix.Import inside the function body. This avoids circular import issues when the MCP server module is imported during testing or introspection. It also makes each tool self-contained.
Everything returns a string. MCP tools communicate over JSON-RPC. The
word_count function returns an int , but the MCP tool returns str(_word_count(text)) . The extract_emails function returns a list[str] , but the MCP tool returns json.dumps(...) . This ensures all tools produce values that serialize cleanly over the protocol.Preserved type annotations. The tool function signatures declare their parameter types (
text: str , max_length: int ). FastMCP uses these to generate JSON Schema for the tool's input schema, which clients use to validate arguments before sending them.Preserved docstrings. The
@mcp.tool() decorator reads the function's docstring and exposes it as the tool description. AI agents see "Convert text to a URL-friendly slug" when discovering tools, which is how they decide whether to call slugify or camel_to_snake .Validation: Everything Still Works
ATX ran the validation command (
pytest tests/ -v ) and confirmed all 10 original tests pass. But it went further, testing the MCP server integration:Check | Result |
|---|---|
Original tests pass (10/10) | PASS |
MCP server imports without error | PASS |
5 tools registered with correct names | PASS |
Tool schemas match function signatures | PASS |
call_tool("slugify", {"text": "Hello World"}) returns "hello-world" | PASS |
call_tool("word_count", {"text": "one two three"}) returns "3" | PASS |
call_tool("extract_emails", {"text": "a@b.com"}) returns '["a@b.com"]' | PASS |
Server starts in stdio mode | PASS |
Resource config://project-info returns pyproject.toml content | PASS |
The original library is untouched. The tests exercise the same functions they always did. The MCP server is a new layer on top, not a replacement.
Edge Case Testing
ATX also validated edge cases through the MCP interface to confirm the thin wrapper pattern handles them correctly:
Tool | Edge Case | Input | Expected Result | Status |
|---|---|---|---|---|
slugify | Empty string | "" | "" | PASS |
slugify | Unicode (accented) | "café résumé" | "cafe-resume" | PASS |
slugify | Special chars only | "@#$%^&*" | "" | PASS |
truncate | Exact boundary | text of length 100, max_length=100 | Original text (no truncation) | PASS |
truncate | Suffix longer than max | "hello" , max_length=2, suffix= "..." | Graceful handling | PASS |
word_count | Whitespace only | " \t\n " | "0" | PASS |
word_count | Single word | "hello" | "1" | PASS |
extract_emails | Mixed case emails | "User@Example.COM" | '["user@example.com"]' | PASS |
extract_emails | Multiple in one line | "a@b.com c@d.org" | Both extracted | PASS |
camel_to_snake | Already snake_case | "already_snake" | "already_snake" | PASS |
camel_to_snake | Consecutive capitals | "getHTTPResponse" | "get_http_response" | PASS |
All edge cases handled correctly. The MCP server inherits the library's robustness because it delegates completely. There is no separate error handling path that could diverge from the library's behavior.
How to Use: Connecting AI Agents
The
mcp-config-snippet.json is the key to client integration. Copy its contents into whatever MCP configuration your tool uses.Kiro
Add to your project's
.kiro/mcp.json :{ "mcpServers": { "string-utils": { "command": "python", "args": ["src/mcp_server.py"], "cwd": "/absolute/path/to/string-utils" } }}Kiro will discover the 5 tools at session start. You can ask it to slugify text, count words, or extract emails, and it will call the tools directly.
Claude Code
Add to
~/.claude/claude_desktop_config.json :{ "mcpServers": { "string-utils": { "command": "python", "args": ["src/mcp_server.py"], "cwd": "/absolute/path/to/string-utils" } }}Amazon Q Developer CLI
Add to the MCP configuration in your IDE settings. The format is identical, the tools are immediately available.
Any MCP-Compatible Client
The configuration pattern is universal. Point the client at the Python executable, give it the server script path, and set the working directory. The server communicates over stdio, which every MCP client supports.
Worth noting: MCP now runs in both directions here. Your library becomes an MCP server that agents call — and AWS Transform itself is now reachable as an MCP server, plus a Kiro Power and agent plugins for Claude, Cursor, and Codex. So you can run the MCP-ification transformation from inside your IDE and then immediately consume the resulting MCP server in the same tool.
What an Agent Session Looks Like
Once connected, an agent can use the tools naturally:
User: What's the slug for "AWS Transform Custom: AI-Powered Code Modernization"?
Agent: [calls slugify tool with text="AWS Transform Custom: AI-Powered Code Modernization"] Result: "aws-transform-custom-ai-powered-code-modernization"
The slug is: aws-transform-custom-ai-powered-code-modernizationUser: How many words in this paragraph? [pastes text]
Agent: [calls word_count tool with the provided text] Result: "47"
That paragraph contains 47 words.User: Extract emails from this support ticket: "Please contact dev@company.io or the team lead at alice.smith@company.io for escalation"
Agent: [calls extract_emails tool] Result: '["dev@company.io", "alice.smith@company.io"]'
Found 2 email addresses: dev@company.io and alice.smith@company.ioThe agent does not write Python code, spin up a REPL, or guess at outputs. It calls the function, gets the result, and uses it. This is the difference MCP makes.
The Resource Bonus: Project Metadata
ATX also exposed a resource at
config://project-info :@mcp.resource("config://project-info")def get_project_info() -> str: """Return project configuration from pyproject.toml.""" with open("pyproject.toml") as f: return f.read()MCP resources are read-only data that clients can access for context. An agent connecting to this server can read the project's metadata (name, version, dependencies, Python version requirement) without parsing files itself. Resources complement tools: tools perform actions, resources provide context.
Scaling: Any Library Can Be MCP-ified
The
project-to-mcp-server TD is not specific to string utilities. It works on any Python library with typed, documented public functions. The pattern is mechanical:- Scan the library for public functions
- Extract signatures, types, and docstrings
- Generate a thin wrapper per function
- Add the MCP dependency
- Create the config snippet
This means you can MCP-ify your internal SDKs, your team's utility libraries, your data processing modules. Anything with a Python function signature can become a tool an AI agent can call.
Publishing for Reuse
atx custom def publish \ --transformation-name "project-to-mcp-server" \ --description "Wrap a Python library as an MCP server using fastmcp" \ --sd .Batch Execution Across Multiple Libraries
for lib in /path/to/libraries/*/; do atx custom def exec \ --transformation-name "project-to-mcp-server" \ --code-repository-path "$lib" \ --build-command "pytest tests/ -v" \ --non-interactive --trust-all-toolsdoneRun it across ten libraries in your org. Each one becomes agent-callable. The TD's lessons accumulate with each execution, handling new edge cases (libraries with class methods, async functions, complex return types) better over time.
The Transformation Definition
For those who want to understand what drives ATX's behavior, here is the TD that powered this transformation:
# Transformation: Wrap Python Library as MCP Server
## ObjectiveTransform a plain Python utility library into an MCP (Model Context Protocol)server using the fastmcp package. Each public function in the library becomesan MCP tool that AI assistants can call directly.
## Steps
### Step 1: Analyze the Library- Read all Python source files in src/- Identify all public functions (not prefixed with _)- Extract function signatures, docstrings, type annotations
### Step 2: Create MCP Server Module- Create src/mcp_server.py- Import fastmcp, create server instance- Wrap each function as @mcp.tool()- Preserve docstrings as tool descriptions- Map type annotations to parameter schemas
### Step 3: Update Dependencies- Add mcp>=1.0.0 to pyproject.toml
### Step 4: Create MCP Configuration- Create mcp-config-snippet.json for client discovery
### Step 5: Validate- pytest tests/ -v passes- MCP server starts without errors- All tools registered with correct schemasThis is what makes ATX's registry valuable. Someone wrote this TD once. It now works for every Python library. The continual learning system adds lessons from each execution, so the TD handles increasingly complex scenarios without manual updates.
Cost Estimate
Agent-minutes are non-deterministic — the same transformation costs different amounts on different runs, and dependency drift can add validation/self-correction cycles. When this post was re-run on current dependencies, ATX detected that
fastmcp 2.x carried CVEs, pinned fastmcp>=3.2.0 , hit the fastmcp 3.x API change ( CallToolResult is no longer subscriptable), fixed its generated tests accordingly, and landed on all tests passing — but that self-correction pushed the run to roughly 30+ agent minutes (on the order of ~$1), not the couple of minutes a clean first pass takes.So treat any single dollar figure here as one data point, not a fixed price. Budget with
--limit , run a pilot to establish your own baseline, and expect more agent-minutes when libraries have moved since the transformation was written. For context: writing and debugging this MCP server by hand still takes a developer meaningfully longer, and ATX absorbs the ramp-up on an unfamiliar protocol.Why Not Just Write the Wrapper by Hand?
For a single 5-function library, you could. The value proposition of ATX here is not about this one library. It is about:
Consistency across libraries. When you MCP-ify 10 libraries by hand, you get 10 slightly different patterns. One developer returns JSON strings, another returns raw objects. One uses top-level imports, another uses deferred imports. The TD enforces one pattern everywhere.
Accumulated knowledge. The TD knows to return strings from all tools (because an earlier execution discovered that returning complex objects breaks serialization). It knows to use deferred imports (because another execution hit circular import issues). You get these lessons for free.
Scale. One library is a 15-minute task. Twenty libraries is a half-day task. With ATX, twenty libraries is twenty 2-minute executions you can run in parallel.
Maintenance. When your library adds a new function, re-run the transformation. It detects the new function and adds a tool for it. No manual bookkeeping.
Beyond String Utils: What Else to MCP-ify
The same TD works for any Python library with typed functions. Consider:
- Data validation libraries: Expose validators as tools so agents can check inputs
- File format converters: Let agents convert between formats directly
- API client SDKs: Expose SDK methods as tools so agents can call your service
- Math/science utilities: Give agents access to domain-specific calculations
- Text processing pipelines: NLP tokenizers, sentiment analyzers, entity extractors
- Infrastructure helpers: AWS resource taggers, config validators, policy checkers
The pattern scales to any library where the functions are pure (or at least have well-defined inputs and outputs). Libraries with side effects (database writes, file system changes) work too, but require more careful consideration of what an agent should be allowed to do.
Getting Started
# Install ATX (requires Node.js 22+)curl -fsSL https://transform-cli.awsstatic.com/install.sh | bash
# Authenticate (configure AWS credentials)aws configure # or set AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY / AWS_REGION
# Navigate to your librarycd your-python-library
# Option 1: Use the existing TDatx custom def exec \ --transformation-name "project-to-mcp-server" \ --code-repository-path . \ --build-command "pytest tests/ -v" \ --non-interactive --trust-all-tools
# Option 2: Interactive (describe what you want)atx> Wrap this library as an MCP server. Each public function should become a tool.One command. Your library is now callable by every AI agent that supports MCP. The functions are the same. The tests still pass. The only difference is that now AI tools can discover and invoke your code directly, without writing import statements or running scripts.
Your library was built for developers. Now it works for agents too.
Resources
- MCP specification: spec.modelcontextprotocol.io
- AWS Transform Custom docs: docs.aws.amazon.com/transform/latest/userguide/custom.html
- ATX pricing: $0.035/agent-minute
References
[2] AWS, "AWS Transform Custom documentation." https://docs.aws.amazon.com/transform/latest/userguide/custom.html
Disclaimer: Opinions expressed are personal and do not represent the official position of any organization. All claims about ATX capabilities are verified against the official documentation .
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article