MCP: Model Context ProtocolMCP Integration with AI AgentsLangChain MCP Integration
How Do You Connect LangChain Agents to MCP Servers?
Question 2 of 43 · Updated
On this page
- Direct answer
- 1. Understand the architecture
- 2. Connection and invocation lifecycle
- 3. Practical Python implementation: local inventory server
- 4. Connect the server to a LangChain agent
- 5. Connecting multiple or remote servers
- 6. Locally tested example: enforce a trusted routing boundary
- 7. Production architecture: an enterprise support agent
- 8. Security and trust boundaries
- 9. Reliability, observability and performance
- 10. Common mistakes and interview follow-ups
- 11. Deployment and test checklist
- Interview-ready answer
How do you connect agents to Model Context Protocol servers?
Direct answer#
Connect a LangChain agent to MCP servers by adding an MCP client or adapter inside the agent's host application, discovering the server's available tools, converting those tools into the framework's tool interface, and passing the approved subset to the agent. When the model requests a tool, the host routes the request to the corresponding MCP server, receives the result, and feeds it back to the model so it can continue the task.
The model does not itself open a socket, start a subprocess, hold credentials, or speak MCP. Your application owns those operations. MCP provides the interoperable boundary between the host and external capabilities; LangChain supplies the agent loop and model-facing tool abstractions. You can use MCP without LangChain, and LangChain agents without MCP.
Version and verification note: This lesson uses the established MCP 2025-06-18 specification as a historical protocol baseline and the LangChain v1-style Python agent interface with the langchain-mcp-adapters MultiServerMCPClient pattern. It does not assert that either is the latest release. Live official documentation and exact current SDK versions could not be checked in this offline session. The SDK examples below were syntax-compiled with Python 3.13.5; the dependencies were unavailable, so no real MCP handshake, LangChain model invocation, or SDK integration test was performed. A separate dependency-free routing example was executed locally with six passing cases. Verify package compatibility and the negotiated MCP specification before deployment.
1. Understand the architecture#
Consider an inventory assistant answering “How many A12 units are in stock?”
User
|
v
LangChain application (MCP host)
|-- Model API: reasoning and tool selection
|-- Agent runtime: tool loop, policy, context
|
+-- MCP adapter / client -> Inventory MCP server -> Inventory service
|
+-- MCP adapter / client -> Orders MCP server -> Order serviceThe host coordinates the model, user consent, and external tools. In the session-oriented baseline, each MCP client connection corresponds to one server; a multi-server adapter manages multiple such connections, not a single protocol session shared by all servers. The MCP server owns the business integration. It exposes operations like stock or order_status and validates requests before accessing its downstream service.
The model sees a description and schema for the exposed tools, not the server's credentials or raw network configuration. The agent runtime translates a model tool call to the framework tool abstraction, which invokes the MCP adapter. In a real application, maintain a trusted mapping from exposed tool names to server identities and server tool names.
2. Connection and invocation lifecycle#
For the historical 2025-06-18 session-oriented specification, the typical sequence is:
- The host selects trusted server configurations and starts a local stdio subprocess or establishes a remote HTTP transport.
- The client sends an initialize request containing its supported protocol version, capabilities and client information. The server returns its selected version, capabilities and server information. The client must handle incompatible versions rather than assume that every version works.
- The client sends notifications/initialized to complete initialization in this baseline.
- If the server advertises tools, the client discovers them using tools/list, following pagination if present. Each tool exposes metadata such as a name, description and input schema.
- The host filters the discovered capabilities using policy, converts supported schemas into the model provider's tool format, and binds them to the agent.
- The model returns a structured request to invoke a tool. The host validates the name, arguments, user authorization and approval requirements.
- The adapter sends tools/call to the correct server. The server checks authorization and validates input, executes the operation, then returns the result.
- The host interprets the result, including protocol errors and tool execution errors, and passes appropriate content back into the agent loop.
- The model either answers or requests another permitted action. The host enforces iteration limits, deadlines and spending limits, then closes or reuses connections according to the adapter and negotiated protocol.
Discovery and invocation may occur in different connections with some adapter configurations. Do not depend on state remaining in a subprocess or connection unless your chosen SDK and protocol support it and you explicitly manage its lifetime.
For example, after initialization, the protocol messages for discovery and calling could look like these (illustrative JSON-RPC messages, not a full transport transcript):
JSON{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}
JSON{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"stock","arguments":{"sku":"A12"}}}
JSON{"jsonrpc":"2.0","id":3,"result":{"content":[{"type":"text","text":"7"}],"isError":false}}
The request ID correlates a response with a request. It is not a durable business operation ID or an idempotency key. The example is intentionally limited to a single text result; SDKs can represent structured or other content types differently, and the exact negotiated revision determines available fields.
3. Practical Python implementation: local inventory server#
This is an SDK integration example for the historical FastMCP and LangChain v1 API style. Use a clean virtual environment and select compatible package releases from the official repositories. The following installation command names the dependencies but is not a tested lockfile:
BASHpython -m venv .venv # Activate the environment for your operating system. python -m pip install mcp langchain langchain-mcp-adapters langchain-openai
For a real release, record exact tested versions in a lockfile. The model integration package must match the selected provider; langchain-openai is included here as one example. Set AGENT_MODEL to a supported provider-qualified tool-capable model identifier, and configure the corresponding model credentials securely outside source code.
Save the following as mcp_q2_server.py:
PYTHONfrom mcp.server.fastmcp import FastMCP mcp = FastMCP('inventory') @mcp.tool() def stock(sku: str) -> int: """Return available stock for a known SKU.""" inventory = {'A12': 7, 'B34': 0} if sku not in inventory: raise ValueError('Unknown SKU') return inventory[sku] if __name__ == '__main__': mcp.run(transport='stdio')
The decorator registers a tool whose typed parameter and docstring help construct a discoverable tool contract. The server owns the inventory lookup; in this example the data is deliberately an in-memory fixture rather than a production database. Notice that B34 legitimately has zero stock while an unknown SKU is an error. These outcomes should not be conflated.
Use stderr or a separate logging facility for server diagnostics: arbitrary stdout prints can corrupt a stdio protocol stream. Launch only trusted executable paths and scripts. Do not allow the model to construct subprocess commands.
4. Connect the server to a LangChain agent#
Save the following beside the server file as mcp_q2_agent.py:
PYTHONimport asyncio import os import sys from pathlib import Path from langchain.agents import create_agent from langchain_mcp_adapters.client import MultiServerMCPClient async def main(): server = Path(__file__).with_name('mcp_q2_server.py').resolve() client = MultiServerMCPClient({ 'inventory': { 'transport': 'stdio', 'command': sys.executable, 'args': [str(server)], } }) tools = await client.get_tools() allowed = [tool for tool in tools if tool.name == 'stock'] if len(allowed) != 1: raise RuntimeError('Expected exactly one stock tool') agent = create_agent(os.environ['AGENT_MODEL'], tools=allowed) result = await agent.ainvoke({ 'messages': [{'role': 'user', 'content': 'How many A12 units are in stock?'}] }) print(result['messages'][-1].content) if __name__ == '__main__': asyncio.run(main())
Run python mcp_q2_agent.py after setting the model configuration and provider credentials. If the selected model chooses the stock tool with SKU A12, and the integration succeeds, the expected business result is 7; the exact natural language answer varies. This is an expected outcome, not an observed SDK execution.
What each step does:
- MultiServerMCPClient describes the trusted inventory server, using the same Python interpreter and an absolute script path.
- get_tools discovers MCP tools and converts them into LangChain-compatible tools.
- The allowlist selects the expected operation and fails closed if discovery returns a missing or ambiguous stock tool. This is a teaching example for one trusted server, not sufficient authorization for multiple untrusted servers.
- create_agent binds approved tools to a tool-capable model.
- ainvoke runs the asynchronous agent loop. The framework handles tool execution when the model requests an allowed tool, then returns the conversation state.
- The final message is displayed. A production system should check actual tool execution and business status instead of assuming a model answer is evidence of successful execution.
Some adapter releases expose stateless tool wrappers that create a fresh MCP session per tool call by default, with explicit client.session support for session-oriented use cases. Check your installed adapter version's API and lifecycle rather than assuming that get_tools establishes a permanent connection. Stateful workflows must retain the appropriate session scope and release it on completion or error. Newer protocol revisions may change lifecycle semantics.
5. Connecting multiple or remote servers#
The integration approach is the same for a remote inventory or orders server: configure a trusted endpoint using a transport supported by both the negotiated protocol and adapter, provide appropriate authentication, discover capabilities and expose only approved tools. Streamable HTTP is a defined transport in the historical baseline; older HTTP+SSE configurations may differ. Adapter configuration keys and aliases are SDK-specific and must be checked against the installed release.
For multiple servers, keep an internal registry such as inventory.stock -> inventory server -> stock, and orders.status -> orders server -> status. The server identity matters. If two servers expose a tool named search, using an unqualified name or silently overwriting one binding could invoke the wrong service. Generate provider-compatible unique aliases and keep their routing map in trusted host configuration. Do not use arbitrary model-generated URLs, server names or aliases as execution targets.
Use separate authorization contexts per server and user or tenant as required. Discover tools under the appropriate identity; never treat discovery as evidence that a user is allowed to execute every advertised operation. Resources and prompts are separate MCP capabilities; a tool adapter does not automatically make every resource or prompt available to the model. Expose them deliberately through the appropriate client APIs and host policy.
This lesson focuses on the end-to-end agent integration. Detailed transport configuration and credential management are separate engineering topics.
6. Locally tested example: enforce a trusted routing boundary#
The following runnable, standard-library-only example demonstrates an application-side policy guard independently of LangChain and MCP SDK versions. Its call function is an injected asynchronous dependency that returns a simplified decoded result dictionary. A real adapter would translate the SDK result to this form and preserve the original error classification and content types. This example does not implement JSON-RPC, MCP authentication, a network transport, or the LangChain agent loop.
PYTHONimport asyncio from collections.abc import Awaitable, Callable async def route(name: str, args: dict, call: Callable[..., Awaitable[dict]]) -> dict: if name != 'inventory.stock': raise PermissionError('Tool not allowed') if set(args) != {'sku'} or type(args['sku']) is not str: raise ValueError('Invalid arguments') if not args['sku'] or len(args['sku']) > 32: raise ValueError('Invalid SKU length') result = await asyncio.wait_for(call('stock', args), timeout=2) if result.get('isError'): raise RuntimeError('Server reported a tool error') return result async def test(): calls = [] async def fake_call(name, args): calls.append((name, args)) if args['sku'] == 'missing': return {'isError': True} return {'content': [{'type': 'text', 'text': '7'}]} result = await route('inventory.stock', {'sku': 'A12'}, fake_call) assert result['content'][0]['text'] == '7' for name, args, error in [ ('inventory.delete', {'sku': 'A12'}, PermissionError), ('inventory.stock', {'sku': 12}, ValueError), ('inventory.stock', {'sku': 'A12', 'extra': 1}, ValueError), ('inventory.stock', {'sku': ''}, ValueError), ('inventory.stock', {'sku': 'missing'}, RuntimeError), ]: try: await route(name, args, fake_call) except error: pass else: raise AssertionError('Expected rejection') assert calls == [('stock', {'sku': 'A12'}), ('stock', {'sku': 'missing'})] print('6 routing cases passed; only 2 permitted requests reached the fake server') if __name__ == '__main__': asyncio.run(test())
Actual local output, Python 3.13.5:
6 routing cases passed; only 2 permitted requests reached the fake serverThe six checks cover a successful request, disallowed operation, invalid type, unexpected field, empty SKU, and server-reported tool error. The test proves the first four invalid requests never reached the fake downstream call and that the server-level error is not treated as success. The two-second wait_for is a local deadline; the timeout path was not exercised in these six checks, and cancellation does not prove that a remote operation stopped. The example does not implement user-specific authorization or fully validate untrusted result shapes. Those must be added at the actual server and host boundary.
7. Production architecture: an enterprise support agent#
Imagine a company with separate inventory, order, and knowledge services. An MCP server for each service exposes a narrow, auditable interface. The LangChain host selects tools appropriate to the authenticated support employee and current conversation.
A customer asks whether a product can ship today. The agent requests stock for the specified SKU, then queries order or delivery eligibility as needed. The host resolves each tool to its configured server. Each server enforces tenant isolation and validates the request using the authenticated identity. The host combines verified business results before the model explains them.
If a server returns an error, the agent should not invent inventory or promise a shipment. It can report that the lookup failed, retry a transient read within a bounded budget, or hand the task to a human. Write operations require explicit policy: for example, an order cancellation may require a confirmation tied to the order ID and authenticated actor. If the call times out, reconcile actual business state before retrying. A JSON-RPC request ID alone does not prevent duplicate cancellations.
8. Security and trust boundaries#
- Keep server URLs, executable paths, secrets and tool mappings in trusted application configuration, never in model-generated commands.
- Use least-privilege credentials and validate the user's authorization on every sensitive operation. Do not pass model provider tokens to an unrelated MCP server.
- For remote deployments, use authenticated TLS endpoints and appropriate protocol-version-specific authorization. For local deployments, limit process environment, filesystem access and permissions.
- Treat tool schemas, descriptions, resources and results as untrusted external data. A tool response claiming to be a system instruction cannot change the host's policies.
- Validate argument types, bounds and domain constraints. Bind tenant identity from trusted session context, not from a model-supplied tenant ID.
- Do not allow arbitrary shell commands, unrestricted queries or file access just because a server advertises them.
- Apply explicit consent and confirmation policies for destructive operations. Tool annotations can inform policy but cannot replace independently enforced authorization.
- Redact secrets from prompts, logs and error messages. Limit tool output size before it enters the model context.
9. Reliability, observability and performance#
An agent integration introduces several latency components: discovery, model inference, adapter conversion, client-server round trips, downstream execution and model interpretation of the result. Cache discovery metadata only within an appropriate authorization and server-version scope. Refresh when supported tool-list change notifications arrive or when the cache expires. Never share user-scoped capability caches indiscriminately across tenants.
Choose connection/session reuse based on actual SDK behavior. Starting a subprocess for every operation can be expensive; persistent state can complicate isolation and recovery. Set budgets for tool rounds, deadlines, concurrency, maximum result size and token usage. Parallelize independent reads only when authorization and consistency allow; serialize dependent operations and side effects where required.
Instrument workflow IDs, selected tool aliases, server identities, protocol versions, latency, retries, and error classifications. Correlate model tool-call IDs with protocol request IDs and downstream business operation IDs without assuming they are the same. Distinguish model selection errors, missing tools, schema errors, transport failures, protocol errors, tool execution errors and business failures.
For example, with illustrative rather than benchmarked timings: discovery 100 ms, initial model call 700 ms, one tool round trip 40 ms, inventory lookup 80 ms, and final model call 500 ms give 1,420 ms end to end, excluding other overhead. Reusing a valid discovery cache saves the 100 ms in this scenario, but does not eliminate model or service latency.
10. Common mistakes and interview follow-ups#
Is an MCP server a model or agent? No. It is a protocol endpoint exposing capabilities. It may internally call a model, but it does not have to.
Does an agent need to use MCP to call functions? No. It can directly call framework tools. MCP is helpful when integrations should be reused across hosts or maintained behind a common protocol boundary.
Does connecting a server automatically expose all capabilities safely? No. Discovery describes what is available, not what should be exposed to the model or what a given user is authorized to do.
Do all MCP tools become ordinary LangChain tools automatically? Only capabilities supported by the chosen adapter and model-facing schema conversion can be represented correctly. Review content conversion, naming and schema limitations.
Does the adapter always preserve state? No. Check whether it creates per-call connections, supports explicit session management or uses newer lifecycle semantics.
What if the server returns tool content but reports isError? Treat it as a tool execution failure, not a successful business result. Handle transport and protocol errors separately.
Why not attach every available tool to the model? Huge tool sets can increase token cost, ambiguity, accidental exposure and routing errors. Select a small task-relevant set using trusted policy, not only semantic relevance.
11. Deployment and test checklist#
Before release, pin actual SDK and provider versions; run the inventory server and client with a supported model or controlled model stub; verify negotiated protocol behavior and tool discovery; verify valid and invalid SKUs, zero stock and unknown SKU; check name collisions across servers; simulate process crashes, timeout and cancellation; verify stale discovery metadata handling; test identity and tenant boundaries; and test malicious tool descriptions and results. For writes, verify confirmation, idempotency and reconciliation behavior. Measure latency and costs with realistic load. A passing mock-routing unit test cannot substitute for a real SDK and protocol compatibility test.
Interview-ready answer#
I connect a LangChain agent to MCP servers through an MCP adapter in the host. I configure trusted local or remote servers, discover their tools using MCP, map approved capabilities into LangChain tools, and bind those to a tool-capable agent. When the model chooses a tool, the runtime validates and authorizes the request, routes it to the corresponding MCP server, handles the result or error, and returns the result to the model. I manage server identity, protocol compatibility, connection lifetime, deadlines, user authorization, and observability separately from model reasoning. MCP standardizes the integration boundary; it does not replace the agent loop or security policy.
References
- 1.MCP specification (2025-06-18)modelcontextprotocol.io
- 2.MCP lifecycle (2025-06-18)modelcontextprotocol.io
- 3.MCP tools (2025-06-18)modelcontextprotocol.io
- 4.Official MCP Python SDKgithub.com
- 5.LangChain MCP adaptersgithub.com
- 6.LangChain MCP integrationdocs.langchain.com
- 7.LangChain agentsdocs.langchain.com
- 8.LangChain API referencereference.langchain.com
Related questions
Explore other topics:Forward Deployed EngineeringAI AgentsLarge Language ModelsRetrieval-Augmented Generation