MCP in Practice: A Guide to Context Engineering Implementation
This article explains how the Model Context Protocol (MCP) supports context engineering in production AI systems. It covers why context delivery is a core bottleneck, how MCP's transport, protocol, and service layers divide responsibilities, and the development essentials of its five core services: resources, tools, prompt templates, sampling, and context confirmation. It also outlines how to combine these services with common frameworks, abstract nine frequent application scenarios, and apply governance and cost-control practices for compute-constrained environments.
1. Why Context Delivery Has Become a Core Bottleneck in AI Engineering
A large model’s capability ceiling depends largely on what it can “see” at the moment of inference. In real enterprise environments, knowledge is scattered across document repositories, business databases, ticketing systems, and internal services; the model itself does not hold this data. The traditional approach of stuffing all information into a prompt at once leads to three direct consequences: the context window is crowded out by redundant information, the compute cost per request rises, and data boundaries become difficult to control.
The goal of context engineering is to deliver the right information to the model at the right moment and with the right granularity, while making this process orchestrable, reusable, and auditable. The Model Context Protocol (MCP) is an open specification built for this goal. It decouples the model side from the data side and uses standardized service interfaces to describe resources, tools, and prompt templates, turning context from passive concatenation into active supply. This is also the key lever for building production-grade AI systems with limited compute: reducing ineffective tokens directly lowers inference costs.
2. Principles: Layered Architecture and Protocol Responsibility Boundaries
The best way to understand the protocol is to break it into three layers.
- Transport layer: responsible for reliable message sending and receiving and session persistence. It is typically implemented over local inter-process communication or remote streaming channels, and must handle connection reuse, heartbeats, and reconnection.
- Protocol layer: defines the envelope structure of requests and responses, capability negotiation, version compatibility, and error semantics. Capability negotiation is especially important: the client must confirm which features the server supports when the session is established, avoiding calls to nonexistent interfaces.
- Service layer: exposes concrete context capabilities, namely five types of services: resources, tools, prompt templates, sampling, and context confirmation.
The responsibilities of the three layers must be strictly separated. The transport layer should not understand business semantics, and the service layer should not assume the form of the underlying channel. The most common failure in engineering practice is pushing business decisions down into the transport layer, so that changing the deployment approach requires rewriting the logic.
3. Development Essentials of the Five Core Services
3.1 Resource Service: Unified Addressing for Read-Only Context
Resources provide addressable content with unique identifiers, suitable for carrying document fragments, table schema descriptions, and configuration snapshots. The design essentials are stable identifiers, versionability, and support for on-demand paginated retrieval, avoiding returning oversized text all at once.
3.2 Tool Service: Keeping Side Effects in a Cage
Tools represent executable actions and produce real side effects. You must declare clear input schemas, timeout and idempotency policies, and enforce permission checks and audit trails for write operations. An illustrative definition is as follows:
@tool(name="query_order_status",input_schema={"order_id": "string"},idempotent=True,timeout_ms=2000,)def query_order_status(order_id: str) -> dict:# Read-only query; return only the minimum necessary fieldsreturn {"status": "shipped", "eta": "2026-08-30"}
3.3 Prompt Template Service: Turning Prompt Engineering into Assets
Templates should be parameterized, testable, and releasable through gradual rollout. They should be managed in the same repository as business code and included in the review process, avoiding prompt strings scattered across many places.
3.4 Sampling Service: Keeping Generation Control on the Host Side
Sampling allows the server to request generation from the host model, but model selection, temperature, and budget are determined by the host policy. This ensures controllable costs and auditable compliance.
3.5 Context Confirmation Service: Letting the Model Request Information Proactively
This is the key to “active delivery.” The model can declare which context it needs, and the host injects it on demand rather than indiscriminately filling the window.
4. Development: Engineering Methods for Working with Common Frameworks
Frameworks differ significantly in their abstraction levels: lightweight UI libraries are suitable for quickly validating interaction patterns; model invocation wrapper libraries are suitable for unified multi-model adaptation; orchestration frameworks are suitable for building multi-step pipelines and state machines; high-performance interface frameworks are suitable for exposing service capabilities as stable endpoints; and multi-agent frameworks are suitable for role division and collaboration. In practice, the recommended approach is “push capabilities down, lift orchestration up”: implement the five services as independent, stateless, independently deployable components, and let the upper orchestration layer compose them on demand. Relevant practices at Baidu AI Cloud also follow this layered approach, using a container platform to host services, object storage to hold resources, and a logging, monitoring, and alerting system to ensure observability.
5. Application: Implementation Abstractions for Nine High-Frequency Scenarios
Setting aside specific product forms, production requirements can be grouped into several common scenarios: agent task execution, visual workflow orchestration, UI automation and regression testing, retrieval-augmented knowledge bases, online information retrieval, multimodal content generation, data querying and analysis, approval and ticketing workflows, and cross-system data synchronization. Their commonality is that they all need to deliver enterprise context to the model through standard interfaces, and all need permission and audit constraints on tool calls.
For implementation, a four-step method is recommended: first define the minimum viable context set, then implement read-only services to validate the pipeline, then gradually open write tools and add idempotency and rollback, and finally connect monitoring metrics (call success rate, average context length, token consumption per request, tool timeout rate) to drive optimization.
6. Governance and Cost Control
The key to production in low-compute environments is not how large the model is, but how clean the context is. Quantifiable measures include filtering and reranking resources before retrieval, producing structured summaries of conversation history, trimming fields from tool returns, and setting budget caps on sampling requests. You should also establish a capability inventory and version compatibility strategy, so that any interface change remains backward compatible through capability negotiation and avoids production breakage. Only when the context pipeline has standardized interfaces, observable metrics, and governance policies does an AI system truly become production-ready.
