Skip to content
ImagineWorld

Bringing MCP Apps to Production

node_idnode-book_learn-model-context-protocol-with-python_chapter-12-bringing-mcp-apps-to-production
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num12
chapter_titleBringing MCP Apps to Production
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 12 — Bringing MCP Apps to Production

Section titled “Chapter 12 — Bringing MCP Apps to Production”

Welcome to the final chapter of this book. Great that you’ve made it this far! You’ve learned how to build both servers and clients and might be wondering how you take that last step toward sharing what you’ve built with the world.

That’s a great question, and this chapter will guide you through all the things you should consider to ensure that your MCP application is well-tested, reliable, secure, and performs well in a production environment. Let’s begin!

This chapter covers the following topics:

  • Architecture and design: Here, we will go through modular design, integration patterns, and specific architectural impact due to AI
  • Packaging and distribution: Here, we will discuss different packaging options, standalone, embedded, deployment channels, and semantic versioning
  • Testing and deployment automation: Here, we will look at different types of testing strategies, such as unit testing, integration testing, and AI testing, and ensure that those tests are used within a CI/CD pipeline to deploy with confidence
  • Operations and observability: Here, we will talk about scaling, resiliency patterns, observability, governance, and future proofing

When designing your MCP application, there are several architectural considerations to keep in mind. These include modular design, integration patterns, and the impact of AI on architecture. In this section, we’ll look at the following topics:

  • Integration patterns: How does MCP fit into your existing architecture, and what patterns can you use to ensure seamless integration?
  • Documentation: How do you document your architecture and design decisions to ensure clarity and maintainability?
  • Architecture review: What are the key aspects to consider when reviewing your architecture to ensure that it meets your requirements and is scalable, maintainable, and secure?

Now that we have an overview, let’s dive into each topic.

MCP comes with its own set of integration patterns to facilitate seamless communication between clients and servers. However, if you use a transport such as Streamable HTTP or SSE, this server is then hosted via a web app using HTTP and most likely organized like a RESTful API. That could mean you need to develop or use specific middleware for web API-to-MCP communication for the sake of logging, security, and more. Here’s how that could work. Note the middleware used in the web API. Also note how the web API is most likely a RESTful API, and the client and server use JSON-RPC, as dictated by the MCP protocol:

Figure 12.1 – Integration patterns flow

Figure 12.1 – Integration patterns flow

In this sequence diagram, you can see how the different components interact with each other. The user makes a request to the web API, which then checks the request against its authentication middleware. If the request is allowed, the web API forwards the request data to the client. The client then communicates with the server using JSON-RPC messages.

It’s important that we document our code well so we understand all the bigger parts and how they fit together. This will help both current and future developers to understand the system and make it easier to maintain and extend.

Documentation is very important, both for developers and users. Well-documented code is easier to understand, maintain, and use. There are different aspects to consider when it comes to documentation:

  • Document code and generate documentation: All code should generally be well documented, which means we should aim to document all the operations on input and output. As developers, we know that out-of-date information is sometimes worse than no documentation, so we should strive to generate documentation from the code. What you’re looking for is to have your code generate documentation in an Open API format, formerly known as Swagger. For example, this piece of code has its routes documented in a way to make it easy for the used framework to generate documentation from it:
    from fastapi import FastAPI
    from pydantic import BaseModel
    from typing import List
    app = FastAPI()
    class Booking(BaseModel):
    id: int
    title: str
    description: str = False
    when: str
    @app.get("/booking/", response_model=Booking, tags=["bookings"],
    summary="Book a trip", description="Lets user book a trip[]")
    def book_trip():
    return Booking(id=1, title="Trip to Paris", description="A
    wonderful trip to Paris", when="2023-09-15")

When the code is documented like so with tags, summary, and more, this will be used to generate Open API documentation automatically. Whatever framework and runtime you go with, make sure your code is easy to document and easy to generate documentation from.

  • Tests are also documentation: Tests are sometimes the best way to understand how a feature is supposed to work. They provide concrete examples of expected behavior and can help clarify the intent behind complex logic. Ensure that you include comprehensive tests that cover various scenarios and edge cases.
  • Include context flow diagrams and edge case handling: Mermaid diagrams are becoming a standard and are also supported by GitHub in terms of rendering various flowcharts, sequence diagrams, and more, so consider Mermaid or another way of creating these diagrams. Seeing how something works visually can save both developers and consumers of the code countless hours.

Your architecture should consider the following:

  • Modular design: Make sure all functionality is separated into logical boundaries so that all areas are in their own modules. Different runtimes do this in different ways, but a good rule of thumb is that your code should be organized in a way that makes it easy to understand and maintain. Additionally, you should aim to keep related code together and minimize dependencies between modules. Finally, there should only be one reason to change, meaning each module should have a single responsibility. For example, you wouldn’t keep parsing logic in the same module as business logic.
  • Validation: Implement robust validation mechanisms to ensure data integrity and correctness. This includes input validation, output validation, and contract validation between different components. There’s also a security aspect to this, as malicious actors may try to exploit vulnerabilities in your system. Python uses Pydantic for data validation and settings management with its MCP SDK Leverage these validation libraries for both input and output to address both correctness and security. Here’s an example of using input validation:
    from mcp.server.fastmcp import FastMCP
    from uuid import uuid4
    mcp = FastMCP(name="Tool Example")
    from pydantic import BaseModel
    class User(BaseModel):
    id: int
    name: str
    email: str
    users = []
    @mcp.tool()
    def create_user(user: User):
    # Create user logic here
    user.id = len(users) + 1
    users.append(user)
    return user
    if __name__ == "__main__":
    print("Starting MCP server...")
    mcp.run()

In this example, you see that there’s a tool called create_user. It takes a User model as input, which will immediately help with validation and serialization. The following payload would lead to a new user being created:

{
"id": 0,
"name": "chris",
"email": "[email protected]"
}

On the other hand, the following payload would lead to a validation error as id is missing:

{
"name": "chris",
"email": "[email protected]"
}

This way, you can set up validation for all incoming data and ensure that only correct data enters your system. Of course, from a business and security standpoint, you can keep adding more validation rules as needed before you end up persisting the data.

  • AI’s impact on architecture: If you ship a client and a server, your client will most likely have access to an AI model, which means there are specific things to consider from an architectural standpoint. This includes how the client communicates with the AI model, how to manage context between the client and server, and how to handle any potential failures or timeouts:
    • Decoupled architecture: Ensure you decouple content management, model invocation, and the UI.
      • Latency and reliability, and impact on UI: Also consider the implications of latency and reliability when designing interactions with the AI model. This means, for example, if the AI model takes time to return a response, ensure that the UI remains responsive and provides feedback to the user. If the AI stops responding due to failure or rate limiting, it needs to be handled gracefully. Also, ensure you have fallback mechanisms such as retry logic and circuit breakers. We’ll talk more about this later in the chapter.
      • Token budgeting: Not only is the token budget something to consider as a running cost for the AI model, but it’s also important from an architectural standpoint, as we will need to implement caching strategies and other mechanisms to optimize token usage.
  • Security: Implement security best practices to protect your application and its data. This includes securing APIs, managing user authentication and authorization, and ensuring data privacy and compliance with regulations. Consider how you can adopt least privilege to minimize access rights for users and services. That means ensuring that users and services only have access to the resources they absolutely need. A consequence of this is that you may need to implement more granular access controls and continuously monitor for any unauthorized access attempts.

Before you even type a single line of code, you need to consider what you’re building. With MCP, you have different options on how to package and distribute your application.

Let’s look at some packaging options.

  • Standalone server: This is designed for public access or for private use. Regardless of private or public access, you need to think about authentication, authorization, and data privacy. But for private distribution within a company or organization, you need to think about discoverability, how internal teams will find and use the service, and also compliance with internal policies.
  • Embedded client/server: Such a system probably consists of a client and a server component, and the client most likely ships with AI capabilities, so make sure you consider the implications of that, such as data privacy and security and responsible AI use, and any regulatory requirements that may apply.

Let’s say your goal is to build an MCP server only; that means you most likely focus on building an API that wasn’t there before you wrap a pre-existing API. With this being MCP, you need to decide where this server is meant to run. Here are some considerations:

  • Local machine: In this case, the server needs to use the STDIO transport. Also, because it runs on a user’s machine, from a security aspect, how can you ensure it’s sandboxed and doesn’t have access to resources it shouldn’t? In fact, should you even allow it to access the network? That’s up to you, but you should consider these aspects. See this filesystem MCP server, where the server comes with configuration that both restricts access, which directories it has access to, and it also ships instructions on how to run it in a container environment to ensure the MCP server has as little access as possible (https://github.com/modelcontextprotocol/servers/tree/main/src/filesystem).
  • Remotely via a URL: If your server is accessed remotely, you might not need to be as much concerned about sandboxing, but you do need to think about authentication and authorization, and every aspect of securing the API endpoint. For authentication/authorization, consider using OAuth2 or API keys, and always validate incoming requests. Additionally, consider role-based access control (RBAC) to ensure that users don’t have more access to various server features than they need. That is, consider whether you need administrator users, normal users, or guest access, and what resources and what type of permission levels everything should have.

In both of these cases, you’re most likely storing the source code in something like GitHub or a similar version-controlled system.

Integrating MCP into your existing architecture requires careful planning. From a distribution standpoint, your MCP implementation will most likely deploy in the same motion as your existing services and apps it’s integrating with. From a code organizational perspective, you can still create them as separate services callable as APIs or a microservices architecture; the choice is yours. What you do need to realize, though, is that shipping an MCP integration means you ship more than a server; you need to ship an MCP client as well. The client will be responsible for communicating with the MCP server, handling requests, and managing context.

When it comes to distribution channels, you have a few options:

  • Package the server as a Docker container: This is a great option if you want to ensure that the server runs in a consistent environment, regardless of where it’s deployed. You can push the Docker image to a container registry such as Docker Hub or GitHub Container Registry, and users can pull and run the container easily. With this option, you should specify how to configure the container and any environment variables that need to be set, as in this example:
    FROM node:22.12-alpine AS builder
    WORKDIR /app
    COPY src/filesystem /app
    COPY tsconfig.json /tsconfig.json
    RUN --mount=type=cache,target=/root/.npm npm install
    RUN --mount=type=cache,target=/root/.npm-production npm ci --ignore-scripts --omit-dev
    FROM node:22-alpine AS release
    WORKDIR /app
    COPY --from=builder /app/dist /app/dist
    COPY --from=builder /app/package.json /app/package.json
    COPY --from=builder /app/package-lock.json /app/package-lock.json
    ENV NODE_ENV=production
    RUN npm ci --ignore-scripts --omit-dev
    ENTRYPOINT ["node", "/app/dist/index.js"]

The preceding example is from the example filesystem MCP server (https://github.com/modelcontextprotocol/servers/tree/main/src/filesystem).

  • Distribute via a package manager: If your server is built with Node.js or Python, you can package it as an npm module or a PyPI package, respectively. This allows users to easily install and manage your server as a dependency in their own projects. The corresponding package manager for.NET would be NuGet, and for Java, it would be Maven or Gradle. Different package managers have different rules for what’s needed to package and distribute your code, but it usually involves the creation of a README file, a license, and compressing the code into a bundle. It’s a great way for users of your MCP server to find and use what you’ve built.
  • Repository distribution: You can also distribute your server by providing access to the source code repository directly. This allows users to clone the repository and build the server themselves, giving them more control over the build process and dependencies. Make sure you provide instructions on how to run it and configure it. This configuration instruction from Playwright’s MCP server (https://github.com/RBC/microsoft-playwright-mcp) is a good example showing how to start using it from a host such as VS Code or Claude Code:
    {
    "mcpServers": {
    "playwright": {
    "command": "npx",
    "args": [
    "@playwright/mcp@latest"
    ]
    }
    }
    }

In this instruction, you see how to start the server using npx and how to provide arguments via args.

Semantic versioning is another thing we should adopt for our code. This is because it makes it easier for both you and the consumer of your code to understand the nature of changes in each release.

It works with the following versions:

  • A major version when you make incompatible API changes
  • A minor version when you add functionality in a backward-compatible manner
  • A patch version when you make backward-compatible bug fixes

How you encode this in your software is to version your software; for example, in version 1.3.0, 1 is the major version, 3 is the minor version, and 0 is the patch version. If you only fix the software by applying a patch, then you should increment it from 1.3.0 to 1.3.1. Adding a new feature should be seen as a minor, so you would increment it from 1.3.0 to 1.4.0. A lot of changes, including changes that make the code break, are seen as a major change, and the version should therefore increase from 1.3.0 to 2.0.0.

By encoding it this way, you create a clear and predictable versioning scheme that communicates the nature of changes to users and developers alike. Developer teams can therefore choose whether to stay on 1.3.x (in which case, they only update the software due to bug fixes and patch changes), or if they want new features but to prioritize stability, they would instead be okay with any version matching 1.x.x, which would allow them to receive new features while still being on a stable base that doesn’t risk breaking changes.

Testing is a crucial part of software development, and it’s especially important when working with AI models. Automated tests help ensure that your code behaves as expected and can catch issues early in the development process. Additionally, deploying your application should be automated to ensure consistency and reliability.

We’ve mentioned testing already as a form of documentation. It’s also a vital part to ensure the code behaves as expected. Make sure that the tests you write are comprehensive and cover various scenarios. Some tests you might consider include the following:

  • Unit tests: These are good for ensuring that individual components work as intended. In the context of MCP, consider breaking out parsing logic into separate modules to facilitate easier testing.
  • Integration tests: These validate the interaction between different components and ensure that they work together as expected. For MCP, if your MCP integration is part of a web application, it could be a good idea to set up end-to-end tests that simulate user interactions with the UI. Such a test would then call a web endpoint, which calls a client, and said client would then call an MCP server feature that processes the request and returns a response.
  • AI tests: As AI models can behave unpredictably, it’s crucial to have tests that specifically validate their outputs. This includes testing for various input scenarios and edge cases, and ensuring that the model’s responses are within acceptable parameters. Consider using techniques such as adversarial testing to probe the model’s weaknesses. Adversarial testing involves creating inputs that are specifically designed to trick the model into making mistakes. It’s also a good idea to have a set of prompts to test against, where the system should work well or should invoke a tool or some other functionality.

Generally, with tests, focus on various aspects such as performance, security, and usability.

Building an app, securing it, architecting well, and logging… all that is good, but without a robust process for deployment, none of that matters. So what’s robust then? Robust in the year 2025 means that we can deploy something at the click of a button, many times a day, and that we do so with a number of guardrails in place. Guardrails are steps where we ensure that tests run and pass, policies are followed, and we’re keeping within certain metrics, for example, we don’t make the code slower, and so on.

There are many choices for how to deploy, such as GitHub Actions or Jenkins. They have one thing in common, though: to deploy, you need to define a pipeline with steps in it and make sure the final step leads to an artifact that either can be deployed or you end up with a new deployment in production.

In addition to being able to deploy, we need to ensure that the deployment process is reliable and can be repeated consistently. Also, mistakes happen, so we need to be able to roll back changes if something goes wrong.

What does all this mean for our code? Well, it usually results in a .yml file being created to represent the pipeline mentioned previously.

Then, you might need a different configuration or a different environment, so that’s also something to keep in mind.

Is this different for MCP compared to normal software? Well, the difference lies in realizing that you may ship AI, and for that reason, you might need a separate deployment pipeline for your AI, looking at performance on models, context management, and more.

Once your application is in production, there’s a set of problems we need to address:

  • Observability: Do you know how your app is doing? Is it under load, is it slow, is it failing, and is it secure?
  • Scalability and resilience: Can your app handle traffic spikes? Can it scale up and down, and is it resilient to failures?
  • Monitoring and feedback: Do you know when something goes wrong? Can you alert the right people, and do you have a feedback loop to improve the app over time?
  • Governance and compliance: Are you compliant with regulations? Do you have the right policies in place, and are you managing data responsibly?
  • Future proofing: Are you prepared for future changes? Can you adapt to new technologies, and are you continuously improving your app?

Do you know how your app is doing, really? If you do, that means you’ve been diligent in terms of adding logging, tracing, and metrics. You have probably added a dashboard so you can easily visualize all that, and you even know where to optimize if needed. Most of us aspire to have that level of knowledge of our app and how it’s doing. When you develop a piece of software at a business, for a client, and so on, there’s a lot at stake. We need to keep the data secure, the app needs to respond at a decent speed and use the resources it’s been constrained with, and it needs to work. It doesn’t sound that hard, right? But it is, especially when you start serving tens of thousands of customers, or even millions. But instead of focusing on how difficult it is to get all this correct, let’s talk about the most important things we need to get in place to at least be able to observe our app:

  • Logging: Logging is crucial for understanding the behavior of your application. It helps understand what goes in, what went out, and hopefully, how long it took through various parts of the app. Having logging at the right places can help you identify bottlenecks and optimize performance. What’s important to consider is the log level (e.g., info, debug, or error) and the context you include (e.g., user ID, request ID, etc.) to make your logs more useful.
  • Tracing: Tracing is essential for understanding the flow of requests through your system. It allows you to see how different services interact and where bottlenecks may occur. Implement distributed tracing to get a complete picture of request paths and latencies. Tracing differs from logging in that it captures the journey of a request. Therefore, it usually contains additional information such as origin, destination, and any intermediate services involved.
  • Metrics: Metrics are about knowing the health, performance, and scalability of your server. Important metrics to capture are therefore CPU and memory usage, request throughput, response time, and even error rate. Capturing all that will provide you with a good understanding of how your system is doing.

For observability, MCP isn’t vastly different from traditional applications, but there are unique aspects to consider, such as model performance and token usage. What could be of particular interest to measure for MCP specifically could be token usage per request versus when it’s being cached or reused. Also, for the sake of logging, MCP has different logs built in that we should leverage to indicate errors, warnings, normal logs, and so on (https://modelcontextprotocol.io/specification/2025-03-26/server/utilities/logging).

Another very important aspect of deploying MCP applications is ensuring that they can scale and remain resilient under load. The problem you’re solving is to ensure the following:

  • Traffic spikes: You can take on a sudden increase in traffic without degrading performance. This is usually business-critical if you’re an e-commerce company and need to be able to handle an increase in purchases during peak shopping times.
  • Scaling up and down: You can efficiently manage resources to handle varying loads.
  • Resilience: You can quickly recover from failures and minimize downtime. Doing this well means the users will barely notice failures or at all. The opposite means the users will experience disruptions and degraded service, and might take their business elsewhere.

Now that we understand the major problems and why we should care about these problems, what’s the solution? For traffic spikes, we need to be able to scale up and down quickly. Most cloud providers have this feature built in. What you need to decide on is how much you want to control this. For example, do you want to specify that scaling should happen on a certain CPU or memory load, or are you okay with the chosen platform to handle this?

Also, as an architect, you could also design so that you, for example, use a message queue over directly talking to a database and so on. There are several ways to go about this, and only you know what size you need to account for:

  • Load balancing: The idea with load balancing is to distribute incoming traffic across multiple instances of your application or service to ensure no single instance is overwhelmed. This improves responsiveness and availability. For the sake of your solution, though, you might treat your application and your AI as separate entities and therefore set up different sets of load-balancing schemes for your MCP server and your AI model endpoints.
  • Rate limiting: Rate limiting is a technique used to control the amount of incoming requests to a service within a specific time frame. This helps prevent abuse, ensures fair usage, and manages API costs. Again, just like load balancing, you might have different schemes for your web app and your AI endpoints.
  • Circuit breakers: The idea behind circuit breakers is to detect failures and prevent the system from making requests that are likely to fail. When a certain threshold of failures is reached, the circuit breaker trips, and subsequent requests are automatically rejected for a period of time. This allows the system to recover and prevents it from being overwhelmed by failed requests. From a user experience standpoint, circuit breakers can help maintain a smooth experience by providing fallback options or graceful degradation when certain services are unavailable.

So, how do we implement these mechanisms? Well, some of them can be done at the application level, while others may require infrastructure support. Here are some strategies:

  • Load balancing: Use a load balancer to distribute traffic across multiple instances of your application or service. This can be done using cloud provider features or dedicated load balancing solutions.
  • Rate limiting: Implement rate limiting at the API gateway or application level to control the number of requests from users or services. This can help prevent abuse and ensure fair usage.
  • Circuit breakers: These can be implemented using an API gateway.

If you’re using a cloud provider, you should be looking into Azure API Management or Amazon API Gateway to implement these strategies effectively. These services will address security, scalability, and reliability concerns, and even have features helping you with AI concerns. What they have in common is that they use a declarative approach to define these strategies. For example, Azure API Management uses XML to define policies for rate limiting, caching, and other features. That makes it easy to apply and configure without changing any code.

So, the recommendation here is to look into your cloud provider of choice and leverage their API management solutions to implement these strategies. Check the links at the end of this chapter in the Resources section for more information.

For monitoring, we’ve alluded to the problems you can run into, such as performance bottlenecks, error rates, and user behavior patterns. Here are some strategies to address these issues:

  • Implement application performance monitoring (APM) tools: Use APM tools to gain insights into performance bottlenecks and error rates.
  • Address error rates: Implement automated error tracking and alerting to quickly identify and resolve issues.
  • User behavior analytics: Leverage analytics tools to understand user interactions and identify potential areas for improvement.
  • AI usage: You want to make sure your AI is used as intended and not being abused or misused, and that it produces the responses you expect. For a solution, you should sample requests and analyze them at regular intervals to ensure compliance with usage policies and performance expectations. Also, add feedback loops in the form of letting users provide input on AI-generated content. Having this in place allows you to perform prompt tuning and context refining. Things you want to set up a system for are also to mitigate prompt injection attacks, unsafe content generation, and other potential risks, such as the mentioning of competitor names and more. Whichever service you end up with should be able to tackle all these.

The major cloud providers have monitoring solutions that can help you set up dashboards, alarms, and more. Also, for AI service usage, there are specialized tools that help you analyze prompts. See more on this in the Resources section in this chapter.

Governance is about ensuring that your application operates within the bounds of legal and ethical standards. How much you need to adhere to these depends on the sector you work in. There’s GDPR for data protection, HIPAA for health information, and other regulations that may apply. Ensure you have a robust compliance framework in place.

From a software standpoint, make it easy to comply with these policies by ensuring you log all interactions and create an audit trail so you know who changed what and when. You might also consider implementing access controls and data encryption to further protect sensitive information. If you are shipping AI, you will need to care about bias and fairness in your models. Therefore, you might need things such as robust system prompts and usage of content safety services that help implement the policy you need to adhere to, whether it’s GDPR or other regulations.

Okay, so you’ve managed to deploy a system that meets your current needs. But what about the future? How can you stay safe, secure, compliant, and whatever else you define as success?

MCP is a fairly young protocol, and as such, it will continue to evolve. You need to keep track of such changes; if there are no constructs you should apply, perhaps there are transports you should stop using (SSE is already deprecated in favor of Streamable HTTP). There might also be new guidance on certain feature usage. You need to stay on top of all of that.

There’s also tooling associated with MCP (for example, the Inspector tool) that may change, with either more tools or how you interact with it changing.

Then, you have the SDKs, as software, which are continuously changing. Some changes are so major that they might break your code. You might consider staying on a certain major version at least for a while, but ensure you get all security updates. Combine this with recognized tools such as Dependabot, GitHub Advanced Security, and more to ensure you make informed choices and know what risks you are taking by staying on a certain SDK version or moving on to a new one.

It’s hard to foresee the future, but you can have a responsible stance on heightened security. Software changes quickly, and new threats are detected regularly. Stay informed about the latest security practices and be ready to adapt your system as needed.

This has been a long chapter with much ground to cover, but hopefully you’ve felt helped by the guidance provided. As long as you’re aware of the problems you face and actively work to address them, then the choice is yours for whether you choose to address them through a library, a cloud service, or something else. You should probably spend more time than you think on security, as it’s becoming a top concern of companies worldwide.

Make sure you plan according to what you need to do before production, in production, and post-production, and prepare for the future. Stay informed. Things will break; the question is how you respond to those breaks and what measures you have in place to mitigate any potential issues.

If you read this far, it means you’ve learned a lot from this book, from building your first server and client, interacting with an LLM, consuming the server with a tool such as VS Code, and finally, deploying it in a responsible manner. Congratulations! I’m also always happy to connect with you on LinkedIn at https://uk.linkedin.com/in/christoffer-noring-3257061.

Here are some useful resources: