Unlocking AI Integration: How the Model Context Protocol (MCP) Bridges LLMs with External Tools
This article introduces the Model Context Protocol (MCP) released by Anthropic, explains its core features and client‑server architecture, walks through building a Go‑based MCP server and client with time, weather, and schedule tools, demonstrates testing with MCP Inspector, and highlights MCP's advantages and typical AI application scenarios.
What is MCP Protocol
1.1 Basic Introduction
MCP (Model Context Protocol) is an open standard released by Anthropic in November 2024 to unify communication between large language models (LLMs) and external data sources or tools. Its core goal is to solve data silos and fragmented integration in AI applications.
1.2 Protocol Features
Traditional APIs require different authentication and data standards for each service, like different locks needing different keys. MCP acts as a universal “USB‑C” for AI models, providing a standardized way for models to interact seamlessly with various data sources and tools. Its main characteristics are:
Standard protocol: AI models can interact with any API or data source.
Common standard: Service providers can expose their AI capabilities via the protocol, building a complete AI ecosystem.
Contextual session preservation: Maintains context across applications/services, enabling multi‑step, unified‑context agents.
1.3 Relationship between AI Agent and MCP
AI Agent is an autonomous system that can achieve specific goals without manual intervention.
AI Agent can use MCP‑described functions to understand context and execute tasks across platforms.
1.4 How MCP Works
MCP follows a client‑server architecture consisting of Host, Client, and Server components.
MCP Host: Receives user queries and interacts with the AI model, acting as a container and coordinator.
MCP Client: Maintains a 1:1 connection with the server and composes applications with different functionalities.
MCP Server: A lightweight program that exposes resources, tools, and prompts through MCP primitives; each program publishes specific capabilities.
Basic workflow:
User sends a request to the MCP client.
The AI model analyzes the request and determines which external tool or data to call.
The model sends a request to the appropriate MCP server.
The server processes the request and returns the result.
The model aggregates the result and replies to the user.
2 Building Your MCP Server
The popular Go implementation is github.com/mark3labs/mcp-go (4.2K stars). The following steps create a simple time‑retrieval service.
1. Get the framework
<code>go get github.com/mark3labs/mcp-go</code>2. Write a tool that returns the current time for a given timezone
<code>// CurrentTimeTool adds a "current time" tool to the server
func CurrentTimeTool(s *server.MCPServer) {
tool := mcp.NewTool(
"current time",
mcp.WithDescription("Get current time with timezone, Asia/Shanghai is default"),
mcp.WithString("timezone", mcp.Required(), mcp.Description("current time timezone")),
)
s.AddTool(tool, currentTimeHandler)
}
// currentTimeHandler implements the tool logic
func currentTimeHandler(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
timezone, ok := request.Params.Arguments["timezone"].(string)
if !ok {
return mcp.NewToolResultError("timezone must be a string"), nil
}
loc, err := time.LoadLocation(timezone)
if err != nil {
return mcp.NewToolResultError(fmt.Sprintf("parse timezone with error: %v", err)), nil
}
t := time.Now().In(loc)
result := fmt.Sprintf("当前时间(%s): %s", loc, t.Format("2006-01-02 15:04:05"))
return mcp.NewToolResultText(result), nil
}
</code>3. Register the tool and start the server
<code>func registerTools() {
s := server.NewMCPServer("Archite_Mcp_Server 🚀", "1.0.0")
tools.CurrentTimeTool(s)
if err := server.ServeStdio(s); err != nil {
fmt.Printf("Server error: %v\n", err)
}
}
</code>Build the executable:
<code>go build -v -o archite_mcp_server</code>3 Building a Test MCP Client
The client initializes, connects, exchanges messages, and closes.
<code>func mcp_client_init() {
mcpClient, err := client.NewStdioMCPClient("/path/to/archite_mcp_server", []string{})
if err != nil { panic(err) }
defer mcpClient.Close()
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
initRequest := mcp.InitializeRequest{}
initRequest.Params.ProtocolVersion = mcp.LATEST_PROTOCOL_VERSION
initRequest.Params.ClientInfo = mcp.Implementation{Name: "Archite_Mcp_Client 🚀", Version: "1.0.0"}
initResult, err := mcpClient.Initialize(ctx, initRequest)
if err != nil { panic(err) }
fmt.Printf("初始化成功,服务器信息: %s %s\n", initResult.ServerInfo.Name, initResult.ServerInfo.Version)
toolRequest := mcp.CallToolRequest{
Request: mcp.Request{Method: "tools/call"},
Params: mcp.CallToolParams{Name: "current time", Arguments: map[string]any{"timezone": "Asia/Shanghai"}},
}
result, err := mcpClient.CallTool(ctx, toolRequest)
if err != nil { panic(err) }
fmt.Println("调用工具结果:", result.Content[0].(mcp.TextContent).Text)
}
</code>Running the client prints the current time for the specified timezone.
4 Testing with MCP Inspector
MCP Inspector is an interactive debugging tool that can launch a proxy server and provide a web UI for testing MCP services.
<code>npx @modelcontextprotocol/inspector</code>After starting, the inspector is reachable at http://127.0.0.1:6274 .
5 Building a Simple Schedule Assistant
Beyond time, we add weather and schedule tools.
5.1 Weather Tool (public cloud API)
The tool accepts a Chinese city name and calls Tencent Cloud’s weather API.
<code>// CurrentWeatherTool adds a "current weather" tool
func CurrentWeatherTool(s *server.MCPServer) {
tool := mcp.NewTool(
"current weather",
mcp.WithDescription("Get current weather with area, 北京 is default, 输入中文城市名称"),
mcp.WithString("city", mcp.Required(), mcp.Description("city name, 北京 is default")),
)
s.AddTool(tool, currentWeatherHandler)
}
</code>The handler builds a signed HTTP request, sends it, and returns the raw response.
5.2 Schedule Tool (private database)
Defines Schedule and Event structs and a tool that looks up a user’s schedule from an in‑memory store.
<code>type Schedule struct {
Username string
Events []Event
}
type Event struct {
StartTime string
EndTime string
Content string
}
func ScheduleTool(s *server.MCPServer) {
tool := mcp.NewTool(
"user schedule",
mcp.WithDescription("Get someone today schedule, Brand is default"),
mcp.WithString("username", mcp.Required(), mcp.Description("Get someone today schedule, Brand is default")),
)
s.AddTool(tool, userScheduleHandler)
}
</code>6 Integrating with a Large Model
After the server is ready, connect it to an LLM (e.g., Claude or Qwen) via the MCP Host. In VSCode, install the Cline extension, configure the model, and add the MCP server as a host. The model can then issue three tool calls—time, weather, and schedule—and synthesize a coherent response.
7 MCP Advantages and Typical Use Cases
7.1 Core Benefits
Breaks data silos by providing a unified protocol for heterogeneous systems.
Supports bidirectional, dynamic interaction (request‑response and push notifications).
Ensures privacy and security through local execution and fine‑grained permission control.
Boosts development efficiency by abstracting communication layers.
7.2 Typical Scenarios
Enhanced intelligent assistants that access real‑time data, perform calculations, query databases, and control devices.
Enterprise knowledge management for building smart knowledge bases, cross‑department data sharing, automated document analysis, and personalized employee support.
Architecture & Thinking
🍭 Frontline tech director and chief architect at top-tier companies 🥝 Years of deep experience in internet, e‑commerce, social, and finance sectors 🌾 Committed to publishing high‑quality articles covering core technologies of leading internet firms, application architecture, and AI breakthroughs.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.