# https://github.com/LeelaissakAttota/mcp-ai-agent 项目说明书

生成时间：2026-05-15 07:01:48 UTC

## 目录

- [Project Introduction](#page-project-introduction)
- [Technology Stack](#page-tech-stack)
- [System Architecture](#page-system-architecture)
- [Agent Workflow](#page-agent-workflow)
- [LangGraph ReAct Agent](#page-langgraph-react-agent)
- [Memory Management](#page-memory-management)
- [MCP Server Integration](#page-mcp-servers)
- [Transport Mechanisms](#page-transport-mechanisms)
- [Installation Guide](#page-installation)
- [Configuration](#page-configuration)

<a id='page-project-introduction'></a>

## Project Introduction

### 相关页面

相关主题：[System Architecture](#page-system-architecture), [Technology Stack](#page-tech-stack)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [README.md](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/README.md)
- [main.py](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)
</details>

# Project Introduction

## Overview

The **mcp-ai-agent** is a multi-server AI agent built using the Model Context Protocol (MCP) that serves as a universal interface for connecting to multiple MCP servers simultaneously. The agent leverages GPT-5 Nano for autonomous reasoning and tool selection, enabling users to query diverse domains—including software library documentation and museum collections—through a natural language interface.

The project demonstrates advanced agentic AI patterns including multi-transport protocol management (STDIO and HTTP), persistent conversation memory, and LangGraph-based ReAct agent architecture.

## Purpose and Scope

The primary purpose of this project is to showcase a **"Universal Interface"** pattern—similar to USB-C for AI systems—capable of:

- Connecting to multiple MCP servers concurrently across different transport protocols
- Autonomously selecting appropriate tools based on user queries
- Maintaining persistent conversation memory across interaction sessions
- Providing a unified natural language interface for multi-domain queries

The scope encompasses integration with two distinct MCP servers:

| Server | Transport Protocol | Domain |
|--------|-------------------|--------|
| Context7 | HTTP (streamable_http) | Software library documentation |
| MetMuseum-MCP | STDIO (via npx) | Metropolitan Museum artwork collection |

## Architecture

### High-Level System Architecture

```mermaid
graph TD
    User[User CLI Interface] --> Agent[LangGraph ReAct Agent]
    Agent --> Model[GPT-5 Nano]
    Model --> ToolSel[Tool Selection]
    ToolSel --> Context7[Context7 Server]
    ToolSel --> MetMuseum[MetMuseum-MCP Server]
    Context7 --> Docs[Library Documentation]
    MetMuseum --> Artworks[400K+ Artworks]
    Agent --> Memory[InMemorySaver]
    Memory --> Thread[Thread-based Memory]
    
    subgraph Transport Layer
        HTTP[HTTP Transport]:::http
        STDIO[STDIO Transport]:::stdio
    end
    
    classDef http fill:#90EE90
    classDef stdio fill:#87CEEB
    
    Agent -.-> HTTP
    Agent -.-> STDIO
```

### Component Architecture

```mermaid
graph TD
    subgraph Main Application
        Main[main.py] --> Client[MultiServerMCPClient]
        Client --> Context7Config[Context7 Config]
        Client --> MetMuseumConfig[MetMuseum Config]
        Client --> Tools[Available Tools]
        Main --> Model[ChatOpenAI]
        Main --> Agent[ReAct Agent]
        Main --> Checkpointer[InMemorySaver]
    end
    
    subgraph MCP Servers
        Context7[Context7 Server] --> URL[https://mcp.context7.com/mcp]
        MetMuseum[MetMuseum-MCP] --> NPX[npx metmuseum-mcp]
    end
    
    Tools --> Agent
    Model --> Agent
    Checkpointer --> Agent
```

## Technology Stack

| Component | Technology | Version |
|-----------|------------|---------|
| Language | Python | 3.10+ |
| MCP Client | langchain-mcp-adapters | Latest |
| Agent Framework | LangGraph | Latest |
| Language Model | OpenAI GPT-5 Nano | - |
| Memory | InMemorySaver | - |
| Async Runtime | asyncio | Built-in |

## Core Components

### MultiServerMCPClient

The `MultiServerMCPClient` from `langchain_mcp_adapters` manages connections to multiple MCP servers simultaneously.

**Configuration Structure:**

```python
client = MultiServerMCPClient({
    "context7": {
        "url": "https://mcp.context7.com/mcp",
        "transport": "streamable_http",
    },
    "met-museum": {
        "command": "npx",
        "args": ["-y", "metmuseum-mcp"],
        "transport": "stdio",
    }
})
```

资料来源：[main.py:45-62]()

### LangGraph ReAct Agent

The agent uses the ReAct (Reasoning + Acting) pattern implemented via `create_react_agent`:

```python
agent = create_react_agent(
    model=openai_model,
    tools=tools,
    checkpointer=checkpointer
)
```

**Agent Capabilities:**

- Receives user queries and generates responses
- Selects appropriate tools based on query context
- Maintains conversation history across interactions
- Returns structured responses with tool execution results

### Persistent Memory System

Conversation memory is managed using `InMemorySaver` with thread-based configuration:

```python
checkpointer = InMemorySaver()
config = {"configurable": {"thread_id": "conversation_id"}}
```

资料来源：[main.py:68-70]()

## Agent Workflow

```mermaid
graph LR
    A[User Query] --> B[GPT-5 Nano Reasoning]
    B --> C{Which Server?}
    C -->|Library Docs| D[Context7 HTTP]
    C -->|Museum Data| E[MetMuseum STDIO]
    D --> F[Tool Execution]
    E --> F
    F --> G[Result Returned]
    G --> H[LLM Response]
    H --> I[Memory Updated]
    I --> J[User Response]
```

**Workflow Steps:**

| Step | Description |
|------|-------------|
| 1 | User submits natural language query |
| 2 | GPT-5 Nano reasons about which MCP server to use |
| 3 | Agent calls appropriate tool(s) on selected server |
| 4 | Tool results are returned to the LLM |
| 5 | LLM generates natural language response |
| 6 | Response is stored in InMemorySaver with thread_id |
| 7 | User receives response with conversation context preserved |

## Integrated MCP Servers

### Context7 Server

| Property | Value |
|----------|-------|
| Transport | HTTP (streamable_http) |
| URL | https://mcp.context7.com/mcp |
| Purpose | LLM-optimized documentation search |
| Domain | Software frameworks and libraries |

### MetMuseum-MCP Server

| Property | Value |
|----------|-------|
| Transport | STDIO |
| Execution | npx metmuseum-mcp |
| Purpose | Access museum artwork collection |
| Domain | Metropolitan Museum of Art |
| Collection Size | 400,000+ artworks |

## Key Features

### Multi-Server Architecture
- Simultaneous connection to multiple MCP servers
- Support for both HTTP and STDIO transport protocols
- Automatic tool discovery and aggregation

### Autonomous Tool Selection
The agent intelligently routes queries to appropriate servers:

```
User: "What is LangChain documentation for agents?"
→ Routes to Context7 → Returns docs

User: "Show me Van Gogh paintings in the Met Museum"
→ Routes to MetMuseum → Returns artwork metadata
```

### Persistent Conversation Memory
- Thread-based conversation management
- Full conversation history preserved across turns
- Context-aware responses using previous interactions

### Asynchronous Operations
- Full async/await implementation
- Non-blocking I/O for MCP server communication
- Efficient concurrent tool execution

## Installation and Setup

### Prerequisites

| Requirement | Command |
|-------------|---------|
| Python | 3.10+ |
| npm | For npx execution |

### Dependencies

```bash
pip install langchain-mcp-adapters langgraph langchain-openai
```

### Environment Configuration

```bash
export OPENAI_API_KEY="your-api-key-here"
```

## Project Structure

```
mcp-ai-agent/
│
├── main.py          # Complete multi-server MCP agent implementation
└── README.md        # Project documentation
```

## Usage Flow

```mermaid
sequenceDiagram
    participant User
    participant CLI
    participant Agent
    participant MCP
    participant Memory
    
    User->>CLI: Start application
    CLI->>Agent: Initial introduction request
    Agent->>MCP: Query available tools
    MCP-->>Agent: Tool definitions
    Agent-->>CLI: Introduction response
    CLI-->>User: Display response
    
    User->>CLI: Ask question
    CLI->>Agent: Forward query
    Agent->>Memory: Check conversation history
    Memory-->>Agent: Previous context
    Agent->>MCP: Execute appropriate tool
    MCP-->>Agent: Tool results
    Agent-->>Memory: Store interaction
    Agent-->>CLI: Response
    CLI-->>User: Display result
```

## Conclusion

The mcp-ai-agent project demonstrates a production-ready implementation of multi-server MCP client architecture with autonomous tool selection. It serves as an educational reference for building agentic AI systems that can:

- Connect to diverse MCP servers across different transport protocols
- Maintain persistent conversation context
- Leverage LLMs for intelligent tool routing
- Provide unified natural language interfaces to complex data sources

资料来源：[README.md:1-100]()

---

<a id='page-tech-stack'></a>

## Technology Stack

### 相关页面

相关主题：[Project Introduction](#page-project-introduction), [LangGraph ReAct Agent](#page-langgraph-react-agent)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [README.md](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/README.md)
- [main.py](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)
</details>

# Technology Stack

## Overview

The mcp-ai-agent project implements a multi-server MCP (Model Context Protocol) client architecture that connects to multiple external MCP servers simultaneously. The technology stack combines modern Python async programming with LangGraph's ReAct agent framework and OpenAI's language models to create an intelligent agent capable of autonomous tool selection across different domains.

**Project Scope**: The agent serves as a "Universal Interface" for AI systems, connecting to MCP servers via different transport protocols while maintaining persistent conversation memory and enabling autonomous tool selection powered by GPT-5 Nano.

资料来源：[README.md:1-20]()

---

## Core Components

### Programming Language

| Attribute | Value |
|-----------|-------|
| Language | Python |
| Version | 3.10+ |
| Paradigm | Async/Await, Object-Oriented |

资料来源：[README.md:45-46]()

### Agent Framework

The project utilizes **LangGraph ReAct** as its agent framework. LangGraph provides a declarative API for building stateful, multi-actor applications with LLMs.

```python
agent = create_react_agent(
    model=openai_model,         # The language model to use
    tools=tools,                # Available tools from MCP servers
    checkpointer=checkpointer   # Memory system for conversation history
)
```

资料来源：[main.py:65-70]()

---

## MCP Client Architecture

### MultiServerMCPClient

The project uses `MultiServerMCPClient` from `langchain-mcp-adapters` to manage connections to multiple MCP servers simultaneously.

```python
client = MultiServerMCPClient(
    {
        "context7": {
            "url": "https://mcp.context7.com/mcp",
            "transport": "streamable_http",
        },
        "met-museum": {
            "command": "npx",
            "args": ["-y", "metmuseum-mcp"],
            "transport": "stdio",
        }
    }
)
```

资料来源：[main.py:24-42]()

### Transport Protocols

The architecture supports dual transport mechanisms:

| Transport | Use Case | Server | Protocol |
|------------|----------|--------|----------|
| **streamable_http** | Remote/Cloud servers | Context7 | HTTP |
| **stdio** | Local Node.js servers | MetMuseum-MCP | stdin/stdout |

资料来源：[README.md:70-85]()

---

## Large Language Model Integration

### OpenAI GPT-5 Nano

| Parameter | Value |
|-----------|-------|
| Provider | OpenAI |
| Model | gpt-5-nano |
| Integration | langchain-openai |

```python
openai_model = ChatOpenAI(
    model="gpt-5-nano",
)
```

资料来源：[main.py:47-50]()

The LLM powers the agent's reasoning capabilities, enabling autonomous tool selection and natural language understanding.

---

## Memory System

### InMemorySaver

The project implements persistent conversation memory using LangGraph's `InMemorySaver`.

```python
checkpointer = InMemorySaver()

config = {"configurable": {"thread_id": "conversation_id"}}
```

| Feature | Implementation |
|---------|----------------|
| Type | In-memory checkpointing |
| Scope | Thread-based conversation persistence |
| Library | langgraph.checkpoint.memory |
| Thread Identifier | Configurable `thread_id` |

资料来源：[main.py:52-55]()

---

## MCP Server Integration

### Context7 Server

| Attribute | Value |
|-----------|-------|
| Type | Remote HTTP Server |
| URL | https://mcp.context7.com/mcp |
| Transport | streamable_http |
| Purpose | LLM-optimized documentation search |

Context7 provides access to documentation across major software frameworks and libraries, enabling the agent to answer code-related queries.

资料来源：[README.md:78-80]()

### MetMuseum-MCP Server

| Attribute | Value |
|-----------|-------|
| Type | Local STDIO Server |
| Command | npx |
| Package | metmuseum-mcp |
| Transport | stdio |
| Purpose | Access to 400,000+ artworks |

The Met Museum MCP server is executed locally via npx and communicates through stdin/stdout, providing access to the Metropolitan Museum of Art collection.

资料来源：[README.md:81-85]()

---

## Architecture Diagram

```mermaid
graph TD
    User[User CLI] --> Agent[LangGraph ReAct Agent]
    Agent --> LLM[GPT-5 Nano]
    Agent --> Tools[All MCP Tools]
    
    subgraph MCP_Clients
        HTTP[HTTP Transport] --> Context7[Context7 Server]
        STDIO[STDIO Transport] --> MetMuseum[MetMuseum-MCP]
    end
    
    Tools --> MCP_Clients
    LLM --> Decision[Tool Selection]
    Decision --> MCP_Clients
    
    Agent --> Memory[InMemorySaver]
    Memory --> Thread[conversation_id]
    
    subgraph External
        Context7 --> Docs[Library Documentation]
        MetMuseum --> Artworks[400K+ Artworks]
    end
```

---

## Workflow Diagram

```mermaid
graph LR
    A[User Query] --> B[GPT-5 Nano Reasoning]
    B --> C{Which Server?}
    C -->|Library/Code| D[Context7 HTTP]
    C -->|Art/Museum| E[MetMuseum STDIO]
    D --> F[Tool Execution]
    E --> F
    F --> G[Result to LLM]
    G --> H[Natural Language Response]
    H --> I[InMemorySaver]
    I --> J[User Receives Response]
```

资料来源：[README.md:28-60]()

---

## Async Programming

### Asyncio Integration

The project leverages Python's `asyncio` for concurrent operations:

```python
async def main():
    # Async operations for MCP client
    client = MultiServerMCPClient({...})
    tools = await client.get_tools()
    
    # Agent invocation
    response = await agent.ainvoke(...)
```

| Component | Async Pattern |
|-----------|---------------|
| MCP Client | `await client.get_tools()` |
| Agent Invocation | `await agent.ainvoke()` |
| Entry Point | `asyncio.run(main())` |

资料来源：[main.py:19-80]()

---

## Skills Demonstrated

The technology stack showcases the following competencies:

| Skill | Implementation |
|-------|----------------|
| Multi-server MCP client architecture | MultiServerMCPClient |
| STDIO + HTTP transport management | Dual protocol support |
| LangGraph ReAct agent with tool calling | create_react_agent |
| GPT-5 Nano integration | ChatOpenAI |
| Persistent conversation memory | InMemorySaver |
| Thread-based conversation management | thread_id config |
| Async Python patterns | asyncio + await |

资料来源：[README.md:62-75]()

---

## Dependencies

| Package | Purpose |
|---------|---------|
| langchain-mcp-adapters | MultiServerMCPClient for MCP server connections |
| langgraph | ReAct agent framework and InMemorySaver |
| langchain-openai | OpenAI model integration |
| npx | Node.js package runner (external) |

资料来源：[README.md:88-91]()

---

## System Architecture Summary

| Layer | Component | Technology |
|-------|-----------|------------|
| Interface | CLI | User input/output |
| Agent | ReAct Agent | LangGraph |
| Reasoning | LLM | OpenAI GPT-5 Nano |
| Memory | Checkpointer | InMemorySaver |
| Integration | MCP Client | langchain-mcp-adapters |
| External Services | Documentation | Context7 (HTTP) |
| External Services | Museum Data | MetMuseum (STDIO) |

---

<a id='page-system-architecture'></a>

## System Architecture

### 相关页面

相关主题：[Agent Workflow](#page-agent-workflow), [Transport Mechanisms](#page-transport-mechanisms), [MCP Server Integration](#page-mcp-servers)

<details>
<summary>Relevant Source Files</summary>

The following source files were used to generate this page:

- [README.md](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/README.md)
- [main.py](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)
</details>

# System Architecture

## Overview

The mcp-ai-agent is a multi-server Model Context Protocol (MCP) client designed to act as a universal interface for AI agents. It simultaneously connects to multiple MCP servers across different transport protocols, providing persistent conversation memory and autonomous tool selection powered by GPT-5 Nano through a LangGraph ReAct agent implementation. 资料来源：[README.md](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/README.md)

## High-Level Architecture

The system follows a layered architecture where the CLI interface communicates with a LangGraph ReAct agent that manages connections to multiple external MCP servers. The agent reasoning engine determines which server to query based on the user's domain, while the checkpointer maintains conversation state across interactions. 资料来源：[README.md](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/README.md)

```mermaid
graph TD
    User[User CLI Interface]
    Agent[LangGraph ReAct Agent]
    MCPClient[MultiServerMCPClient]
    Context7[Context7 Server]
    MetMuseum[MetMuseum-MCP Server]
    
    User -->|"User Query"| Agent
    Agent -->|"Tool Execution"| MCPClient
    MCPClient -->|"HTTP Transport"| Context7
    MCPClient -->|"STDIO Transport"| MetMuseum
    Agent -->|"Memory"| InMemorySaver[InMemorySaver]
    
    subgraph "Transport Layer"
        Context7
        MetMuseum
    end
```

## Core Components

### MultiServerMCPClient

The MultiServerMCPClient from the `langchain-mcp-adapters` package handles simultaneous connections to multiple MCP servers using different transport protocols. This component abstracts the complexity of managing HTTP and STDIO connections, providing a unified interface for tool retrieval. 资料来源：[main.py:24](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

| Server | Transport Type | Purpose |
|--------|---------------|---------|
| Context7 | `streamable_http` | Remote cloud-based library documentation search |
| MetMuseum-MCP | `stdio` | Local museum collection access via npx |

### Configuration Parameters

| Parameter | Value | Description |
|-----------|-------|-------------|
| `context7.url` | `https://mcp.context7.com/mcp` | Endpoint for Context7 MCP server |
| `context7.transport` | `streamable_http` | HTTP-based communication protocol |
| `met-museum.command` | `npx` | Node.js package runner |
| `met-museum.args` | `["-y", "metmuseum-mcp"]` | Auto-install and execute MetMuseum MCP |
| `met-museum.transport` | `stdio` | Standard input/output protocol |

资料来源：[main.py:28-42](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

### LangGraph ReAct Agent

The agent is created using LangGraph's `create_react_agent` factory function, combining the OpenAI language model with retrieved MCP tools and a checkpointer for conversation persistence. The ReAct (Reasoning + Acting) pattern enables the agent to reason about which tools to invoke before executing them. 资料来源：[main.py:56-61](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

```python
agent = create_react_agent(
    model=openai_model,         # GPT-5 Nano reasoning engine
    tools=tools,                # Available tools from MCP servers
    checkpointer=checkpointer   # Memory system for conversation history
)
```

### Language Model Integration

The system uses OpenAI's GPT-5 Nano model through the `langchain_openai` package, configured with minimal parameters for cost-effective reasoning. 资料来源：[main.py:44-46](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

```python
openai_model = ChatOpenAI(
    model="gpt-5-nano",  # Using OpenAI's GPT-5 Nano model
)
```

### Conversation Memory System

The InMemorySaver checkpointer provides thread-based conversation persistence. All messages within a session share the same `thread_id`, enabling the agent to maintain context across multiple user queries. 资料来源：[main.py:48-52](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

```python
checkpointer = InMemorySaver()
config = {"configurable": {"thread_id": "conversation_id"}}
```

## Agent Workflow

```mermaid
graph TD
    A[User Query] --> B[GPT-5 Nano Reasoning]
    B --> C{Which Server Has Info?}
    C -->|"Code/Library Docs"| D[Context7 HTTP]
    C -->|"Art/Museum Data"| E[MetMuseum STDIO]
    D --> F[Tool Execution]
    E --> F
    F --> G[Result to LLM]
    G --> H[LLM Generates Response]
    H --> I[Store in InMemorySaver]
    I --> J[User Receives Response]
```

### Workflow Steps

1. **User Query**: The CLI receives a natural language question from the user
2. **LLM Reasoning**: GPT-5 Nano analyzes the query to determine which MCP server contains relevant information
3. **Tool Selection**: The agent autonomously selects the appropriate server based on domain classification
4. **Tool Execution**: The selected MCP server is invoked via its transport protocol
5. **Result Processing**: Tool results are returned to the LLM for natural language synthesis
6. **Memory Storage**: The complete conversation exchange is persisted via InMemorySaver
7. **Response Delivery**: The user receives the formatted response with preserved context

资料来源：[README.md](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/README.md)

## Transport Protocols

### HTTP Transport (Context7)

The Context7 server uses `streamable_http` transport for remote cloud communication. This transport is optimized for latency-sensitive operations and supports scalable server deployments. 资料来源：[main.py:29-31](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

```python
"context7": {
    "url": "https://mcp.context7.com/mcp",
    "transport": "streamable_http",
}
```

### STDIO Transport (MetMuseum)

The MetMuseum MCP server uses `stdio` transport for local process communication. The server is launched via `npx` and communicates through standard input/output streams. 资料来源：[main.py:33-36](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

```python
"met-museum": {
    "command": "npx",
    "args": ["-y", "metmuseum-mcp"],
    "transport": "stdio",
}
```

## Async Architecture

The entire system is built on Python's `asyncio` framework, enabling concurrent handling of multiple MCP server connections and non-blocking I/O operations. The main entry point uses `asyncio.run()` to execute the async `main()` function. 资料来源：[main.py:1](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

```python
import asyncio

async def main():
    # Async MCP client initialization
    client = MultiServerMCPClient({...})
    
    # Async tool retrieval
    tools = await client.get_tools()
    
    # Async agent invocation
    response = await agent.ainvoke({"messages": query}, config=config)

if __name__ == "__main__":
    asyncio.run(main())
```

## Interaction Flow

```mermaid
sequenceDiagram
    participant User
    participant CLI
    participant Agent
    participant MCPClient
    participant Server
    
    User->>CLI: Enter question
    CLI->>Agent: ainvoke(query)
    Agent->>MCPClient: get_tools()
    MCPClient->>Server: HTTP/STDIO Request
    Server->>MCPClient: Tool Response
    MCPClient->>Agent: Results
    Agent->>Agent: Generate natural language
    Agent->>CLI: Formatted response
    CLI->>User: Display response
```

## Dependency Stack

| Layer | Technology | Version | Purpose |
|-------|-----------|---------|---------|
| Language | Python | 3.10+ | Runtime environment |
| MCP Client | langchain-mcp-adapters | Latest | Multi-server MCP connections |
| Agent Framework | langgraph | Latest | ReAct agent orchestration |
| LLM Integration | langchain-openai | Latest | OpenAI API wrapper |
| Runtime | npx/Node.js | Latest | Local MCP server execution |

资料来源：[README.md](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/README.md)

## System Initialization Sequence

```python
# 1. Create MCP client with server configurations
client = MultiServerMCPClient(servers)

# 2. Initialize the language model
openai_model = ChatOpenAI(model="gpt-5-nano")

# 3. Retrieve all tools from connected servers
tools = await client.get_tools()

# 4. Set up conversation memory
checkpointer = InMemorySaver()

# 5. Create configuration with thread ID
config = {"configurable": {"thread_id": "conversation_id"}}

# 6. Build the ReAct agent
agent = create_react_agent(model, tools, checkpointer)
```

资料来源：[main.py:23-61](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

## Autonomous Tool Selection

The agent demonstrates intelligent routing based on query domain classification:

| Query Type | Target Server | Example |
|------------|---------------|---------|
| Documentation/Code | Context7 | "What LangGraph tools are available?" |
| Art/Museum | MetMuseum | "Show me Van Gogh paintings" |

This autonomous selection is powered by GPT-5 Nano's reasoning capabilities, eliminating the need for explicit routing logic in the application code. 资料来源：[README.md](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/README.md)

---

<a id='page-agent-workflow'></a>

## Agent Workflow

### 相关页面

相关主题：[System Architecture](#page-system-architecture), [LangGraph ReAct Agent](#page-langgraph-react-agent), [Memory Management](#page-memory-management)

<details>
<summary>Relevant Source Files</summary>

以下源码文件用于生成本页说明：

- [main.py](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)
- [README.md](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/README.md)
</details>

# Agent Workflow

The **Agent Workflow** in this MCP AI agent project defines how a user query flows through the system—from initial reasoning by the language model to autonomous tool selection and execution across multiple MCP servers, ultimately producing a contextual response with persistent conversation memory.

---

## Overview

The agent functions as a **Universal Interface** built on the Model Context Protocol (MCP), connecting simultaneously to multiple MCP servers across different transport protocols. It combines **GPT-5 Nano reasoning** with **autonomous tool selection** and **persistent conversation memory** to deliver intelligent, domain-aware responses.

资料来源：[README.md](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/README.md)

---

## High-Level Architecture

```mermaid
graph TD
    User[User Query] --> CLI[CLI Interface]
    CLI --> Agent[LangGraph ReAct Agent]
    
    Agent --> LLM[GPT-5 Nano<br/>Reasoning Engine]
    LLM --> Decision{Which Server?}
    
    Decision -->|Library/Code Docs| Context7[Context7 Server<br/>HTTP Transport]
    Decision -->|Art/Museum Data| MetMuseum[MetMuseum-MCP<br/>STDIO Transport]
    
    Context7 --> Tools1[Documentation Tools]
    MetMuseum --> Tools2[Artwork Tools]
    
    Tools1 --> Result1[Result Returned]
    Tools2 --> Result2[Result Returned]
    
    Result1 --> LLM
    Result2 --> LLM
    
    LLM --> Response[Natural Language<br/>Response]
    Response --> Memory[InMemorySaver<br/>thread_id]
    Memory --> User
    
    style User fill:#e1f5fe
    style Agent fill:#fff3e0
    style LLM fill:#f3e5f5
    style Memory fill:#e8f5e9
```

资料来源：[README.md](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/README.md)

---

## Workflow Stages

### 1. User Query Input

The workflow begins when a user submits a natural language query through the CLI interface. The agent presents a menu with two options:

| Option | Action |
|--------|--------|
| `1` | Ask the agent a question |
| `2` | Quit |

资料来源：[main.py:44-48](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

### 2. GPT-5 Nano Reasoning

The submitted query is passed to **GPT-5 Nano** via the `ChatOpenAI` model. The LLM performs reasoning to determine:

- The intent of the user's question
- Which domain the query belongs to
- Which MCP server has the relevant information

```python
openai_model = ChatOpenAI(
    model="gpt-5-nano",
)
```

资料来源：[main.py:60-62](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

### 3. Autonomous Tool Selection

Based on the reasoning, the agent autonomously selects the appropriate MCP server:

```mermaid
graph LR
    Query1["Query about code libraries<br/>e.g., 'LangGraph tools'"] --> Decision1{Decision}
    Query2["Query about artworks<br/>e.g., 'Van Gogh paintings'"] --> Decision1
    
    Decision1 -->|Code/Docs| C7[Context7 Server<br/>streamable_http]
    Decision1 -->|Museum Data| MM[MetMuseum-MCP<br/>stdio via npx]
    
    C7 --> ToolsC7[Documentation<br/>Search Tools]
    MM --> ToolsMM[Artwork Metadata<br/>& Images Tools]
```

| Server | Transport | Use Case |
|--------|-----------|----------|
| **Context7** | `streamable_http` | Software framework documentation, library references |
| **MetMuseum-MCP** | `stdio` | Museum artwork metadata, images, collections |

资料来源：[main.py:38-55](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/README.md)

### 4. Tool Execution

Tools are retrieved from both MCP servers via `MultiServerMCPClient` and attached to the agent:

```python
client = MultiServerMCPClient({
    "context7": {
        "url": "https://mcp.context7.com/mcp",
        "transport": "streamable_http",
    },
    "met-museum": {
        "command": "npx",
        "args": ["-y", "metmuseum-mcp"],
        "transport": "stdio",
    }
})

tools = await client.get_tools()
```

资料来源：[main.py:38-55](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

### 5. Result Processing

After tool execution, results are returned to the LLM, which generates a natural language response incorporating the retrieved data.

### 6. Response Delivery

The final response is displayed to the user, and the conversation is stored in memory:

```python
response = await agent.ainvoke(
    {"messages": query},
    config=config
)
print(response['messages'][-1].content)
```

资料来源：[main.py:68-72](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

---

## Core Components

### LangGraph ReAct Agent

The agent is created using `create_react_agent` from LangGraph, combining reasoning and acting capabilities:

| Component | Purpose |
|-----------|---------|
| `model` | GPT-5 Nano for LLM reasoning |
| `tools` | All tools from MCP servers |
| `checkpointer` | InMemorySaver for memory |

```python
agent = create_react_agent(
    model=openai_model,
    tools=tools,
    checkpointer=checkpointer
)
```

资料来源：[main.py:64-68](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

### Persistent Conversation Memory

The `InMemorySaver` provides thread-based conversation persistence:

```python
checkpointer = InMemorySaver()
config = {"configurable": {"thread_id": "conversation_id"}}
```

| Feature | Description |
|---------|-------------|
| Memory Type | In-memory (volatile) |
| Persistence Scope | Thread-based via `thread_id` |
| Use Case | Multi-turn conversations |

资料来源：[main.py:63-65](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

### Multi-Server MCP Client

The `MultiServerMCPClient` manages connections to multiple servers simultaneously:

| Server | Transport | Protocol |
|--------|-----------|----------|
| Context7 | Remote HTTP | `streamable_http` |
| MetMuseum-MCP | Local STDIO | `npx` command |

资料来源：[main.py:38-55](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

---

## Interaction Flow

```mermaid
sequenceDiagram
    participant User
    participant Agent
    participant LLM
    participant Context7
    participant MetMuseum
    participant Memory

    User->>Agent: Submit query
    Agent->>LLM: Reason about query intent
    LLM-->>Agent: Select appropriate server
    
    alt Code/Documentation Query
        Agent->>Context7: Call documentation tools
        Context7-->>Agent: Return documentation
    else Museum Query
        Agent->>MetMuseum: Call artwork tools
        MetMuseum-->>Agent: Return artwork data
    end
    
    Agent->>LLM: Generate response with context
    LLM-->>Agent: Natural language response
    Agent->>Memory: Store in thread
    Agent-->>User: Display response
    
    Note over User,Memory: Full conversation history preserved
```

资料来源：[README.md](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/README.md)

---

## System Prompt Configuration

The agent's behavior is defined through a system message:

```python
response = await agent.ainvoke(
    {"messages": [
        {"role": "system", "content": "You are a smart, useful agent with tools to access code library documentation and the Met Museum collection."},
        {"role": "user", "content": "Give a brief introduction of what you do and the tools you can access."},
    ]},
    config=config
)
```

| Message Type | Purpose |
|--------------|---------|
| `system` | Defines agent role and capabilities |
| `user` | Initial introduction request |

资料来源：[main.py:74-81](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

---

## Execution Model

The application uses Python's `asyncio` for asynchronous execution:

```python
async def main():
    # Async operations for MCP client
    # Agent invocation with tools
    pass

if __name__ == "__main__":
    asyncio.run(main())
```

| Pattern | Usage |
|---------|-------|
| `async/await` | Non-blocking I/O for MCP servers |
| `asyncio.run()` | Entry point for async execution |

资料来源：[main.py:30-89](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

---

## Example Workflow Scenarios

### Scenario 1: Documentation Query

| Step | Action |
|------|--------|
| 1 | User asks: "What LangGraph tools are available?" |
| 2 | LLM reasons → selects Context7 |
| 3 | Context7 returns LangGraph documentation |
| 4 | Agent generates response |
| 5 | Response stored in memory |

### Scenario 2: Museum Collection Query

| Step | Action |
|------|--------|
| 1 | User asks: "Show me Impressionist paintings from the Met" |
| 2 | LLM reasons → selects MetMuseum-MCP |
| 3 | MetMuseum returns artwork metadata |
| 4 | Agent generates response |
| 5 | Response stored in memory |

资料来源：[README.md](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/README.md)

---

## Technology Stack Summary

| Component | Technology | Role |
|-----------|------------|------|
| Language | Python 3.10+ | Runtime |
| MCP Client | langchain-mcp-adapters | Server connectivity |
| Agent Framework | LangGraph ReAct | Tool-augmented reasoning |
| LLM | OpenAI GPT-5 Nano | Natural language understanding |
| Memory | InMemorySaver | Conversation persistence |
| Transport 1 | streamable_http | Remote server communication |
| Transport 2 | stdio | Local server communication |

资料来源：[README.md](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/README.md)

---

<a id='page-langgraph-react-agent'></a>

## LangGraph ReAct Agent

### 相关页面

相关主题：[Agent Workflow](#page-agent-workflow), [Memory Management](#page-memory-management), [MCP Server Integration](#page-mcp-servers)

<details>
<summary>Related Source Files</summary>

The following source files were used to generate this page:

- [main.py](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)
- [README.md](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/README.md)
</details>

# LangGraph ReAct Agent

## Overview

The LangGraph ReAct Agent is the core reasoning and decision-making engine in the `mcp-ai-agent` project. It combines the **ReAct** (Reasoning + Acting) pattern with LangGraph's stateful graph architecture to create an autonomous agent capable of selecting and executing tools from multiple MCP (Model Context Protocol) servers.

**Key Responsibilities:**

- Reasoning about user queries to determine which tools to invoke
- Coordinating with multiple MCP servers across different transport protocols
- Maintaining conversation history through persistent memory
- Generating natural language responses based on tool execution results

**资料来源：** [README.md](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/README.md)

---

## Architecture

### System Overview

The agent operates within a multi-server MCP client architecture that connects to both remote and local MCP servers:

```mermaid
graph TD
    User[User Query] --> CLI[CLI Interface]
    CLI --> Agent[LangGraph ReAct Agent]
    Agent --> MCPClient[MultiServerMCPClient]
    MCPClient --> HTTP[HTTP Transport]
    MCPClient --> STDIO[STDIO Transport]
    HTTP --> Context7[Context7 Server]
    STDIO --> MetMuseum[MetMuseum MCP Server]
    Context7 --> Docs[Library Documentation]
    MetMuseum --> Artworks[Met Museum Collection]
    Agent <--> Memory[InMemorySaver]
```

**资料来源：** [README.md:1-80](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/README.md)

### Agent Creation Pipeline

```mermaid
graph LR
    A[ChatOpenAI Model] --> B[create_react_agent]
    C[MCP Tools] --> B
    D[InMemorySaver] --> B
    B --> E[ReAct Agent]
```

**资料来源：** [main.py:46-56](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

---

## Core Components

### Component Configuration

| Component | Class | Purpose |
|-----------|-------|---------|
| **MCP Client** | `MultiServerMCPClient` | Manages connections to multiple MCP servers |
| **Agent** | `create_react_agent` | ReAct-style agent with tool-calling capabilities |
| **Memory** | `InMemorySaver` | Persistent conversation history storage |
| **LLM** | `ChatOpenAI` | Language model for reasoning and response generation |
| **Checkpointer** | `InMemorySaver` | Thread-based conversation state persistence |

**资料来源：** [main.py:17-21](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

### MCP Server Configuration

| Server | Transport | Type | Capabilities |
|--------|-----------|------|--------------|
| **context7** | `streamable_http` | Remote/HTTP | LLM-optimized documentation search |
| **met-museum** | `stdio` | Local/STDIO | Metropolitan Museum artwork access |

**资料来源：** [main.py:29-43](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

---

## Agent Initialization

### Step 1: MCP Client Setup

```python
client = MultiServerMCPClient({
    "context7": {
        "url": "https://mcp.context7.com/mcp",
        "transport": "streamable_http",
    },
    "met-museum": {
        "command": "npx",
        "args": ["-y", "metmuseum-mcp"],
        "transport": "stdio",
    }
})
```

The `MultiServerMCPClient` simultaneously manages:

- **HTTP Transport**: Used for remote servers like Context7
- **STDIO Transport**: Used for local servers like MetMuseum-MCP (via npx)

**资料来源：** [main.py:29-43](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

### Step 2: Tool Retrieval

```python
tools = await client.get_tools()
```

All tools from both MCP servers are aggregated into a single tool collection that the agent can invoke.

**资料来源：** [main.py:48-49](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

### Step 3: Memory Checkpointer

```python
checkpointer = InMemorySaver()
config = {"configurable": {"thread_id": "conversation_id"}}
```

The `InMemorySaver` provides in-memory persistence for conversation threads, enabling the agent to maintain context across multiple interactions.

**资料来源：** [main.py:51-54](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

### Step 4: Agent Creation

```python
agent = create_react_agent(
    model=openai_model,
    tools=tools,
    checkpointer=checkpointer
)
```

The agent is created using LangGraph's `create_react_agent` factory with the OpenAI model, aggregated tools, and memory checkpointer.

**资料来源：** [main.py:56-60](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

---

## Workflow

### Query Processing Flow

```mermaid
graph TD
    A[User Query] --> B{Parse Query}
    B -->|Library/Code docs| C[Call Context7 Tools]
    B -->|Art/Museum data| D[Call MetMuseum Tools]
    C --> E[Tool Execution]
    D --> E
    E --> F[Result returned to LLM]
    F --> G[Generate Natural Language Response]
    G --> H[Store in InMemorySaver]
    H --> I[Return Response to User]
```

**资料来源：** [README.md:35-50](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/README.md)

### Autonomous Tool Selection

The agent independently decides which MCP server to query based on the user's query:

| Query Type | Selected Server | Example |
|------------|-----------------|---------|
| Documentation | Context7 | "What is the LangChain documentation for agents?" |
| Artwork | MetMuseum | "Show me Van Gogh paintings in the Met Museum" |

**资料来源：** [README.md:70-82](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/README.md)

### Message Handling

```mermaid
sequenceDiagram
    participant User
    participant CLI
    participant Agent
    participant Memory
    participant MCP_Servers

    User->>CLI: Enter query
    CLI->>Agent: ainvoke with query + config
    Agent->>Memory: Check conversation history
    Memory-->>Agent: Previous messages
    Agent->>MCP_Servers: Select and call appropriate tool
    MCP_Servers-->>Agent: Tool result
    Agent->>Memory: Store updated conversation
    Agent-->>CLI: Response with context
    CLI-->>User: Display final response
```

**资料来源：** [main.py:64-90](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

---

## Configuration Reference

### Model Configuration

| Parameter | Value | Description |
|-----------|-------|-------------|
| `model` | `gpt-5-nano` | OpenAI GPT-5 Nano model for reasoning |

**资料来源：** [main.py:45-46](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

### Conversation Configuration

| Parameter | Key | Value | Description |
|-----------|-----|-------|-------------|
| `configurable` | `thread_id` | `"conversation_id"` | Groups all messages in a session |

**资料来源：** [main.py:53-54](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

### System Prompt

The agent is initialized with a system message defining its role:

```
You are a smart, useful agent with tools to access code library documentation and the Met Museum collection.
```

**资料来源：** [main.py:68-69](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

---

## Usage Patterns

### Initial Introduction

```python
response = await agent.ainvoke(
    {"messages": [
        {"role": "system", "content": "You are a smart, useful agent..."},
        {"role": "user", "content": "Give a brief introduction..."},
    ]},
    config=config
)
print(response['messages'][-1].content)
```

**资料来源：** [main.py:65-75](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

### Query Invocation

```python
response = await agent.ainvoke(
    {"messages": query},
    config=config
)
print(response['messages'][-1].content)
```

The response contains all messages; the final message (`[-1]`) holds the agent's natural language response.

**资料来源：** [main.py:81-88](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

---

## Dependencies

| Package | Purpose |
|---------|---------|
| `langchain-mcp-adapters` | MultiServerMCPClient for MCP server connections |
| `langgraph` | create_react_agent, InMemorySaver |
| `langchain-openai` | ChatOpenAI integration |

**资料来源：** [main.py:17-21](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py), [README.md:87-92](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/README.md)

---

## Key Features

| Feature | Implementation | Benefit |
|---------|---------------|---------|
| Multi-transport support | Simultaneous HTTP + STDIO | Connect to diverse MCP servers |
| Persistent memory | InMemorySaver with thread_id | Maintains conversation context |
| Autonomous tool selection | GPT-5 Nano reasoning | LLM decides which server to query |
| ReAct pattern | create_react_agent | Combines reasoning with tool execution |
| Async architecture | asyncio + await | Non-blocking concurrent operations |

**资料来源：** [README.md:95-107](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/README.md)

---

<a id='page-memory-management'></a>

## Memory Management

### 相关页面

相关主题：[LangGraph ReAct Agent](#page-langgraph-react-agent), [Agent Workflow](#page-agent-workflow)

<details>
<summary>Relevant Source Files</summary>

The following source files were used to generate this documentation:

- [main.py](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)
</details>

# Memory Management

## Overview

The mcp-ai-agent implements a **persistent conversation memory system** using LangGraph's checkpointing infrastructure. This system enables the AI agent to maintain context across multiple interaction turns within a single conversation session, ensuring coherent and contextually aware responses.

Memory management is critical for multi-turn conversations where the agent needs to reference previous user queries, tool invocations, and generated responses to provide meaningful follow-up interactions.

---

## Architecture

### System Components

| Component | Type | Purpose | Source |
|-----------|------|---------|--------|
| `InMemorySaver` | Checkpointer | Stores conversation state in memory | [main.py](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py) |
| `thread_id` | Configuration Key | Groups messages into conversation threads | [main.py](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py) |
| `config` | Dictionary | Carries configurable parameters to agent | [main.py](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py) |
| `checkpointer` | Parameter | Attaches memory to ReAct agent | [main.py](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py) |

### Memory Flow Architecture

```mermaid
graph TD
    A[User Query 1] --> B[Agent Invocation]
    B --> C[InMemorySaver Checkpointer]
    C --> D[Memory Storage]
    D --> E[Response Generated]
    
    F[User Query 2] --> G[Agent Invocation with Config]
    G --> C
    C --> H[Retrieve Prior Conversation State]
    H --> I[Full Context Available]
    I --> J[Context-Aware Response]
    
    E --> D
    J --> D
```

---

## Core Components

### InMemorySaver

The `InMemorySaver` class from `langgraph.checkpoint.memory` provides the foundational memory storage mechanism.

```python
from langgraph.checkpoint.memory import InMemorySaver

checkpointer = InMemorySaver()
```

**Characteristics:**

| Property | Value |
|----------|-------|
| Storage Type | In-memory (volatile) |
| Persistence | Session-scoped only |
| Scope | Single Python process |
| Serialization | Automatic by LangGraph |

资料来源：[main.py:1-3](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

### Thread Configuration

Each conversation is associated with a unique thread identifier, enabling isolation between different user sessions.

```python
config = {"configurable": {"thread_id": "conversation_id"}}
```

**Configuration Parameters:**

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `thread_id` | string | "conversation_id" | Unique identifier for the conversation thread |

资料来源：[main.py:58-60](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

### Agent Integration

The checkpointer is attached to the ReAct agent during initialization, binding the memory system to the agent's lifecycle.

```python
agent = create_react_agent(
    model=openai_model,
    tools=tools,
    checkpointer=checkpointer
)
```

资料来源：[main.py:63-67](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

---

## Memory Lifecycle

```mermaid
sequenceDiagram
    participant User
    participant CLI
    participant Agent
    participant Checkpointer
    participant LLM

    User->>CLI: Enter query
    CLI->>Agent: ainvoke with config + query
    Agent->>Checkpointer: Load thread state
    Checkpointer-->>Agent: Prior messages
    Agent->>LLM: Full context + new query
    LLM-->>Agent: Generated response
    Agent->>Checkpointer: Save updated state
    Agent-->>CLI: Response
    CLI-->>User: Display result
```

### Initialization Phase

During agent initialization, the checkpointer is configured:

1. `InMemorySaver` instance is created
2. Configuration dictionary is prepared with `thread_id`
3. Agent is created with checkpointer attached

资料来源：[main.py:52-67](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

### Query Processing Phase

Each incoming query triggers the following memory operations:

1. Agent receives query with configuration containing `thread_id`
2. Checkpointer loads all prior messages from the thread
3. Full conversation history is prepended to current query
4. LLM generates response with complete context
5. New messages are appended to thread state
6. Updated state is persisted via checkpointer

资料来源：[main.py:76-86](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

---

## Usage Pattern

### Basic Implementation

```python
# Import the checkpointer
from langgraph.checkpoint.memory import InMemorySaver

# Create in-memory storage
checkpointer = InMemorySaver()

# Define thread configuration
config = {"configurable": {"thread_id": "user_session_123"}}

# Attach to agent
agent = create_react_agent(
    model=openai_model,
    tools=tools,
    checkpointer=checkpointer
)

# Query with memory preservation
response = await agent.ainvoke(
    {"messages": query},
    config=config
)
```

### Multi-Turn Conversation Example

```python
# First turn - agent introduces itself
response = await agent.ainvoke(
    {"messages": [
        {"role": "system", "content": "You are a smart agent..."},
        {"role": "user", "content": "Introduce yourself"}
    ]},
    config=config
)

# Second turn - user asks follow-up question
response = await agent.ainvoke(
    {"messages": "What tools can you use?"},
    config=config
)
# Agent remembers the introduction from turn 1
```

资料来源：[main.py:69-86](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

---

## Configuration Options

### Thread Management

| Option | Description | Use Case |
|--------|-------------|----------|
| Static `thread_id` | Fixed identifier for entire session | Single continuous conversation |
| Dynamic `thread_id` | Generated per user/session | Multi-user applications |
| Per-invocation `config` | Separate config each call | Complex state management |

### Memory Configuration Structure

```python
config = {
    "configurable": {
        "thread_id": str,          # Required: conversation identifier
        # Additional configurable fields can be added here
    }
}
```

---

## State Storage Model

### Persisted State Components

The checkpointer automatically stores:

| State Component | Description | Example |
|-----------------|-------------|---------|
| Message History | All conversation messages | System, user, assistant, tool messages |
| Tool Call Results | Responses from MCP tool invocations | Documentation search results, artwork data |
| Agent Memory | Intermediate agent reasoning state | ReAct thought processes |

### State Access Pattern

```mermaid
graph LR
    A[Query N] --> B[Load State: Messages 1 to N-1]
    B --> C[LLM Processing]
    C --> D[Generate Response]
    D --> E[Save State: Messages 1 to N]
    E --> F[Return to User]
```

---

## Limitations

| Limitation | Impact | Mitigation |
|------------|--------|------------|
| In-memory only | Data lost on process restart | Not suitable for production requiring persistence |
| Single-process | Cannot scale across instances | Use database-backed checkpointers for distributed systems |
| Memory-bound | Large conversations consume RAM | Implement conversation truncation for extended sessions |

---

## Integration with MCP Tools

The memory system works seamlessly with MCP server tool calls:

```python
# When user queries about library docs:
# 1. Memory loads prior conversation
# 2. Agent decides to call Context7 tools
# 3. Tool results stored in conversation state
# 4. Agent generates response referencing full history

# When user queries about museum artworks:
# 1. Memory loads prior conversation
# 2. Agent decides to call MetMuseum tools
# 3. Tool results stored in conversation state
# 4. Agent generates contextually aware response
```

资料来源：[README.md](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/README.md)

---

## Dependencies

| Package | Version | Purpose |
|---------|---------|---------|
| `langgraph` | Latest | Core agent framework with checkpointing |
| `langgraph.checkpoint.memory` | Included | InMemorySaver implementation |

资料来源：[main.py:3](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

---

## Summary

The Memory Management system in mcp-ai-agent provides:

- **Conversation persistence** via thread-based state storage
- **Context preservation** across multiple interaction turns
- **Seamless integration** with LangGraph ReAct agent architecture
- **Automatic state management** through the checkpointer interface

This system enables the agent to maintain coherent, context-aware conversations while preserving the full history of tool invocations and responses within each session.

---

<a id='page-mcp-servers'></a>

## MCP Server Integration

### 相关页面

相关主题：[Transport Mechanisms](#page-transport-mechanisms), [System Architecture](#page-system-architecture)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [main.py](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)
- [README.md](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/README.md)
</details>

# MCP Server Integration

## Overview

The MCP Server Integration module serves as the core connectivity layer that enables the AI agent to communicate with multiple external services simultaneously. This integration leverages the **Model Context Protocol (MCP)** to establish connections between the agent and various MCP-compliant servers, providing access to diverse data sources and capabilities through a unified interface.

The integration supports both **HTTP** and **STDIO** transport protocols, allowing the agent to connect to remote cloud-based servers and local Node.js-based MCP servers concurrently. This dual-transport architecture enables seamless access to documentation services, museum collections, and other specialized data providers without requiring the agent to manage multiple connection protocols manually.

资料来源：[main.py:28-42](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

---

## Architecture

### High-Level System Design

The MCP Server Integration follows a client-server architecture where the `MultiServerMCPClient` acts as a central hub managing multiple server connections. The client aggregates tools from all configured servers and exposes them to the LangGraph ReAct agent for autonomous tool selection based on user queries.

```mermaid
graph TD
    subgraph Agent["LangGraph ReAct Agent"]
        LLM["GPT-5 Nano<br/>Reasoning Engine"]
        Tools["Aggregated Tools"]
        Mem["InMemorySaver<br/>Conversation Memory"]
    end
    
    subgraph Client["MultiServerMCPClient"]
        HTTP["HTTP Transport<br/>Manager"]
        STDIO["STDIO Transport<br/>Manager"]
    end
    
    subgraph Servers["MCP Servers"]
        C7["Context7 Server<br/>(Remote HTTP)"]
        MET["MetMuseum-MCP<br/>(Local STDIO)"]
    end
    
    User["User Query"]
    Response["AI Response"]
    
    User --> LLM
    LLM --> Tools
    Tools --> HTTP
    Tools --> STDIO
    HTTP --> C7
    STDIO --> MET
    C7 --> Response
    MET --> Response
    LLM --> Mem
    
    style Client fill:#e1f5fe
    style Servers fill:#fff3e0
```

资料来源：[README.md](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/README.md)

### Component Responsibilities

| Component | Responsibility | Transport Type |
|-----------|----------------|----------------|
| `MultiServerMCPClient` | Manages concurrent server connections and tool aggregation | Both |
| `create_react_agent` | Creates the ReAct agent with integrated tools | N/A |
| `InMemorySaver` | Maintains conversation history per thread | N/A |
| `ChatOpenAI` | Powers reasoning and natural language generation | N/A |

资料来源：[main.py:35-54](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

---

## Server Configuration

### Configuration Structure

The MCP server integration uses a dictionary-based configuration passed to `MultiServerMCPClient`. Each server entry requires a transport specification and associated connection parameters.

```python
client = MultiServerMCPClient({
    "server_name": {
        "transport": "transport_type",
        # Transport-specific parameters
    }
})
```

资料来源：[main.py:29-42](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

### Supported Transport Types

| Transport | Use Case | Configuration Parameters |
|-----------|----------|-------------------------|
| `streamable_http` | Remote cloud servers | `url` (endpoint URL) |
| `stdio` | Local Node.js servers | `command`, `args` (executable and arguments) |

资料来源：[README.md](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/README.md)

### Context7 Server Configuration

The Context7 server provides LLM-optimized documentation search capabilities across major software frameworks and libraries.

```python
"context7": {
    "url": "https://mcp.context7.com/mcp",
    "transport": "streamable_http",
}
```

| Parameter | Value | Description |
|-----------|-------|-------------|
| Server Name | `context7` | Unique identifier for the server |
| URL | `https://mcp.context7.com/mcp` | Remote HTTP endpoint |
| Transport | `streamable_http` | HTTP-based MCP protocol |

资料来源：[main.py:31-34](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

### MetMuseum-MCP Server Configuration

The MetMuseum server provides access to the Metropolitan Museum of Art collection, including artwork metadata and images.

```python
"met-museum": {
    "command": "npx",
    "args": ["-y", "metmuseum-mcp"],
    "transport": "stdio",
}
```

| Parameter | Value | Description |
|-----------|-------|-------------|
| Server Name | `met-museum` | Unique identifier for the server |
| Command | `npx` | Node.js package runner |
| Arguments | `["-y", "metmuseum-mcp"]` | Flags and package name |
| Transport | `stdio` | Standard input/output protocol |

资料来源：[main.py:36-41](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

---

## Tool Integration

### Tool Retrieval

Tools are retrieved asynchronously from all configured MCP servers using the `get_tools()` method. This aggregation happens at initialization time, making all tools available to the agent without manual registration.

```python
tools = await client.get_tools()
```

资料来源：[main.py:47](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

### Tool Selection Workflow

The ReAct agent autonomously selects the appropriate tool based on the user's query. The LLM reasoning engine analyzes the query and determines which MCP server's tools are relevant.

```mermaid
graph TD
    A["User Query"] --> B["LLM Analyzes Query"]
    B --> C{"Query Domain?"}
    C -->|Library/Code Docs| D["Select Context7 Tools"]
    C -->|Art/Museum Data| E["Select MetMuseum Tools"]
    D --> F["Execute Tool Call"]
    E --> F
    F --> G["Return Result to LLM"]
    G --> H["Generate Natural Language Response"]
    H --> I["User Response + Context"]
```

资料来源：[README.md](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/README.md)

### Example Tool Selection Scenarios

| User Query | Selected Server | Available Actions |
|------------|-----------------|-------------------|
| "What is the LangChain documentation for agents?" | Context7 | Documentation search |
| "Show me Van Gogh paintings in the Met Museum" | MetMuseum | Artwork metadata retrieval |
| "Explain LangGraph state management" | Context7 | Framework-specific docs |

---

## Agent Creation and Binding

### ReAct Agent Construction

The agent is created using LangGraph's `create_react_agent` factory function, which binds the language model, tools, and checkpointer into a single executable agent instance.

```python
agent = create_react_agent(
    model=openai_model,         # GPT-5 Nano reasoning engine
    tools=tools,                # All tools from MCP servers
    checkpointer=checkpointer   # Conversation memory
)
```

资料来源：[main.py:49-53](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

### Parameter Specifications

| Parameter | Type | Description |
|-----------|------|-------------|
| `model` | `ChatOpenAI` | GPT-5 Nano instance for reasoning |
| `tools` | `List[BaseTool]` | Aggregated tools from all MCP servers |
| `checkpointer` | `InMemorySaver` | Thread-based conversation persistence |

---

## Conversation Memory Management

### Thread Configuration

Each conversation session uses a unique `thread_id` to maintain context across multiple interactions. The checkpointer stores all messages in memory for the duration of the session.

```python
config = {"configurable": {"thread_id": "conversation_id"}}
```

资料来源：[main.py:55-56](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

### Memory Flow

```mermaid
graph LR
    A["User Message"] --> B["Agent Processing"]
    B --> C["Tool Execution"]
    C --> D["Result Storage"]
    D --> E["InMemorySaver"]
    E --> F["Response to User"]
    F --> G["Next User Message"]
    G --> E
```

资料来源：[main.py:50-56](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

---

## Initialization Sequence

### Async Startup Flow

The application follows a specific initialization sequence to ensure all components are properly configured before handling user queries.

```mermaid
sequenceDiagram
    participant Main as main.py
    participant Client as MultiServerMCPClient
    participant LLM as ChatOpenAI
    participant Agent as ReAct Agent
    participant User as User
    
    Main->>Client: Initialize with server config
    Main->>LLM: Create GPT-5 Nano instance
    Main->>Client: await get_tools()
    Client-->>Main: Return aggregated tools
    Main->>Agent: Create with model + tools + checkpointer
    Agent-->>Main: Agent ready
    Main->>Agent: Send introduction message
    Agent-->>User: Display capabilities
    User->>Agent: Submit query
    Agent-->>User: Return response
```

资料来源：[main.py:27-72](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

### Startup Steps

| Step | Action | Code Reference |
|------|--------|----------------|
| 1 | Import dependencies | `main.py:13-18` |
| 2 | Create MCP client | `main.py:29-42` |
| 3 | Initialize LLM | `main.py:44-46` |
| 4 | Retrieve tools | `main.py:47` |
| 5 | Create checkpointer | `main.py:49` |
| 6 | Configure thread | `main.py:55-56` |
| 7 | Create agent | `main.py:51-53` |

---

## Dependencies

### Required Python Packages

| Package | Purpose | Import Statement |
|---------|---------|------------------|
| `langchain-mcp-adapters` | Multi-server MCP client | `from langchain_mcp_adapters.client import MultiServerMCPClient` |
| `langgraph` | ReAct agent framework | `from langgraph.prebuilt import create_react_agent` |
| `langgraph.checkpoint.memory` | Conversation memory | `from langgraph.checkpoint.memory import InMemorySaver` |
| `langchain-openai` | OpenAI integration | `from langchain_openai import ChatOpenAI` |

资料来源：[main.py:13-17](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

### External Requirements

| Requirement | Purpose | Version |
|-------------|---------|---------|
| Python | Runtime environment | 3.10+ |
| Node.js | Required for npx command | Latest stable |
| npx | Package runner for local MCP servers | Bundled with Node.js |

资料来源：[README.md](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/README.md)

---

## Error Handling and Edge Cases

### Transport-Specific Considerations

| Transport | Potential Issues | Mitigation |
|-----------|------------------|------------|
| `streamable_http` | Network connectivity, server availability | Timeout handling, retry logic |
| `stdio` | Node.js installation, package availability | npx `-y` flag for auto-installation |
| Both | Server timeout | Async/await with proper exception handling |

资料来源：[main.py:36-41](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

---

## Security Considerations

### API Key Management

The integration requires an OpenAI API key for the GPT-5 Nano model. The key should be set as an environment variable rather than hardcoded in the source.

```bash
export OPENAI_API_KEY="your-api-key-here"
```

资料来源：[README.md](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/README.md)

### Transport Security

| Transport | Security Model |
|-----------|----------------|
| HTTP | Relies on HTTPS/TLS for data-in-transit encryption |
| STDIO | Local execution with user permissions |

---

## Extensibility

### Adding New MCP Servers

To extend the integration with additional MCP servers:

1. Add server configuration to the `MultiServerMCPClient` dictionary
2. Specify the appropriate transport type (`streamable_http` or `stdio`)
3. Provide required connection parameters
4. Tools will be automatically aggregated on next `get_tools()` call

```python
client = MultiServerMCPClient({
    "context7": {...},
    "met-museum": {...},
    "new_server": {
        "url": "https://new-server.endpoint.com/mcp",
        "transport": "streamable_http",
    }
})
```

资料来源：[main.py:29-42](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

---

<a id='page-transport-mechanisms'></a>

## Transport Mechanisms

### 相关页面

相关主题：[MCP Server Integration](#page-mcp-servers), [System Architecture](#page-system-architecture)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [main.py](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)
- [README.md](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/README.md)
</details>

# Transport Mechanisms

## Overview

Transport mechanisms are the communication protocols that enable the MCP AI Agent to connect with external MCP (Model Context Protocol) servers. This project implements a **multi-transport architecture** that supports simultaneous connections to both remote and local MCP servers, allowing the agent to access diverse tools and data sources through a unified interface.

The transport layer abstracts the underlying communication details, enabling the agent to interact with different server types using a consistent tool interface while the agent reasoning engine autonomously selects the appropriate transport based on query domain.

资料来源：[main.py:1-70](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

## Architecture

### Multi-Transport Client Design

The `MultiServerMCPClient` from `langchain-mcp-adapters` serves as the central transport orchestration component. It manages concurrent connections to multiple MCP servers using different transport protocols while exposing a unified `tools` interface to the agent.

```mermaid
graph TD
    A[LangGraph ReAct Agent] --> B[MultiServerMCPClient]
    B --> C[HTTP Transport Layer]
    B --> D[STDIO Transport Layer]
    C --> E[Context7 Server<br/>Remote/Cloud]
    D --> F[MetMuseum-MCP<br/>Local/npx]
    
    style C fill:#e1f5fe
    style D fill:#fff3e0
```

资料来源：[main.py:41-55](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

## Supported Transport Types

### STDIO Transport

The STDIO (Standard Input/Output) transport is designed for local MCP servers that run as child processes on the same machine. Communication occurs through stdin and stdout streams, making it ideal for servers that are invoked via command-line tools.

#### Configuration Parameters

| Parameter | Type | Description | Example |
|-----------|------|-------------|---------|
| `command` | string | Executable command to launch the server | `"npx"` |
| `args` | array | Command-line arguments passed to the executable | `["-y", "metmuseum-mcp"]` |
| `transport` | string | Must be set to `"stdio"` | `"stdio"` |

#### Use Case

The STDIO transport is used for the **MetMuseum-MCP** server, which is executed locally via `npx`. This approach allows the agent to access over 400,000+ artworks from the Metropolitan Museum of Art collection without requiring a separate server process.

资料来源：[main.py:49-54](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)
资料来源：[README.md](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/README.md)

### HTTP Transport (Streamable HTTP)

The HTTP transport enables communication with remote MCP servers over HTTP/HTTPS protocols. This transport type supports cloud-based or network-accessible MCP servers that expose REST-like endpoints.

#### Configuration Parameters

| Parameter | Type | Description | Example |
|-----------|------|-------------|---------|
| `url` | string | Full URL endpoint of the MCP server | `"https://mcp.context7.com/mcp"` |
| `transport` | string | Must be set to `"streamable_http"` | `"streamable_http"` |

#### Use Case

The HTTP transport is used for the **Context7** server, which provides LLM-optimized documentation search across major software frameworks and libraries. This remote server is accessed via the `streamable_http` protocol for efficient streaming responses.

资料来源：[main.py:45-48](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)
资料来源：[README.md](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/README.md)

## Transport Configuration

### Complete Configuration Structure

The MCP client is initialized with a dictionary mapping server names to their transport configurations:

```python
client = MultiServerMCPClient({
    "context7": {
        "url": "https://mcp.context7.com/mcp",
        "transport": "streamable_http",
    },
    "met-museum": {
        "command": "npx",
        "args": ["-y", "metmuseum-mcp"],
        "transport": "stdio",
    }
})
```

### Server Comparison

| Attribute | Context7 | MetMuseum-MCP |
|-----------|----------|---------------|
| Transport Type | HTTP | STDIO |
| Location | Remote/Cloud | Local |
| Invocation | Direct URL | npx command |
| Data Domain | Library documentation | Artwork/Museum data |
| Server Process | Hosted service | Spawned child process |

资料来源：[main.py:41-55](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

## Tool Aggregation

The `MultiServerMCPClient.get_tools()` method retrieves all available tools from all configured MCP servers, regardless of their transport type. This aggregation enables the LangGraph ReAct agent to have a unified toolset while each tool maintains its underlying transport implementation.

```python
tools = await client.get_tools()
```

The aggregated tools are then passed to the LangGraph agent:

```python
agent = create_react_agent(
    model=openai_model,
    tools=tools,
    checkpointer=checkpointer
)
```

资料来源：[main.py:56-68](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

## Transport Selection Workflow

The agent autonomously determines which transport/server to use based on the user's query. The selection occurs during the LLM reasoning phase of the ReAct agent loop.

```mermaid
graph TD
    A[User Query] --> B[GPT-5 Nano Reasoning]
    B --> C{Query Domain Analysis}
    C -->|Code/Library docs| D[HTTP Transport<br/>Context7]
    C -->|Art/Museum| E[STDIO Transport<br/>MetMuseum]
    D --> F[Execute Tool]
    E --> F
    F --> G[Return Result to LLM]
    G --> H[Generate Response]
```

资料来源：[README.md](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/README.md)

## Error Handling Considerations

When working with multiple transport mechanisms, consider the following potential failure points:

| Transport | Potential Issues | Mitigation |
|-----------|------------------|------------|
| STDIO | npx not installed, package not found | Ensure Node.js and npx are available |
| STDIO | Process spawning failures | Check system permissions and PATH |
| HTTP | Network connectivity issues | Verify internet access and URL |
| HTTP | Server availability | Implement retry logic if needed |

资料来源：[main.py:49-54](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

## Dependencies

The transport mechanism implementation requires the following packages:

| Package | Purpose |
|---------|---------|
| `langchain-mcp-adapters` | Provides `MultiServerMCPClient` for multi-transport management |
| `langgraph` | Agent framework with tool calling support |
| `langchain-openai` | OpenAI model integration |

Installation command:

```bash
pip install langchain-mcp-adapters langgraph langchain-openai
npm install -g npx
```

资料来源：[README.md](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/README.md)

## Extending with Additional Transports

To add support for additional MCP servers with different transport types, extend the `MultiServerMCPClient` configuration dictionary:

```python
client = MultiServerMCPClient({
    # Existing servers...
    "new-server": {
        # For HTTP-based servers
        "url": "https://example.com/mcp",
        "transport": "streamable_http",
        
        # OR for STDIO-based servers
        "command": "python",
        "args": ["-m", "my_mcp_server"],
        "transport": "stdio",
    }
})
```

资料来源：[main.py:41-55](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

---

<a id='page-installation'></a>

## Installation Guide

### 相关页面

相关主题：[Configuration](#page-configuration)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [README.md](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/README.md)
- [main.py](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)
</details>

# Installation Guide

## Overview

This guide provides complete instructions for setting up the mcp-ai-agent project locally. The mcp-ai-agent is a multi-server Model Context Protocol (MCP) client that connects to external MCP servers (Context7 and MetMuseum) to enable an AI agent with access to library documentation and museum collections.

资料来源：[README.md](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/README.md)

## Prerequisites

Before installing the mcp-ai-agent, ensure your development environment meets the following requirements:

| Requirement | Minimum Version | Purpose |
|-------------|-----------------|---------|
| Python | 3.10+ | Runtime environment |
| pip | Latest | Python package management |
| Node.js | Recent | Required for npx command |
| npx | Available | Running MetMuseum MCP server |

资料来源：[README.md](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/README.md)

## Project Architecture

The installation involves configuring multiple components that work together:

```mermaid
graph TD
    A[User Environment] --> B[Python 3.10+]
    A --> C[Node.js + npx]
    B --> D[mcp-ai-agent]
    C --> E[MetMuseum-MCP Server]
    D --> F[langchain-mcp-adapters]
    D --> G[LangGraph]
    D --> H[langchain-openai]
    F --> I[MultiServerMCPClient]
    I --> E
    I --> J[Context7 Server<br/>Remote HTTP]
```

## Installation Steps

### Step 1: Install Dependencies

Install the required Python packages using pip:

```bash
pip install langchain-mcp-adapters langgraph langchain-openai
```

Install npx globally for the MetMuseum MCP server:

```bash
npm install -g npx
```

资料来源：[README.md](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/README.md)

### Step 2: Configure Environment Variables

Set your OpenAI API key as an environment variable. This key is required for the agent to communicate with OpenAI's GPT-5 Nano model:

```bash
export OPENAI_API_KEY="your-api-key-here"
```

**Important:** Replace `your-api-key-here` with your actual OpenAI API key.

资料来源：[README.md](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/README.md)

### Step 3: Verify Installation Structure

The project has a minimal structure consisting of two files:

```
mcp-ai-agent/
├── main.py          # Complete multi-server MCP agent
└── README.md
```

资料来源：[README.md](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/README.md)

### Step 4: Run the Agent

Execute the main script to start the agent:

```bash
python main.py
```

资料来源：[README.md](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/README.md)

## MCP Server Configuration

The agent automatically configures connections to two MCP servers during initialization:

### MultiServerMCPClient Setup

The configuration in `main.py` establishes connections to both servers:

```python
client = MultiServerMCPClient({
    "context7": {
        "url": "https://mcp.context7.com/mcp",
        "transport": "streamable_http",
    },
    "met-museum": {
        "command": "npx",
        "args": ["-y", "metmuseum-mcp"],
        "transport": "stdio",
    }
})
```

资料来源：[main.py](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

### Server Configuration Reference

| Server | Transport | Connection Type | Purpose |
|--------|-----------|-----------------|---------|
| Context7 | streamable_http | Remote/Cloud | LLM-optimized documentation search |
| MetMuseum | stdio | Local (npx) | Metropolitan Museum artwork access |

## Required Python Packages

| Package | Version | Role |
|---------|---------|------|
| langchain-mcp-adapters | Latest | MCP client for multi-server connections |
| langgraph | Latest | ReAct agent framework |
| langchain-openai | Latest | OpenAI GPT model integration |

资料来源：[main.py](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

## Post-Installation Verification

After installation, the agent will:

1. Display an introduction message
2. Show available tools from connected MCP servers
3. Present an interactive menu

Expected output:

```
Agent introduces itself and available tools...

Menu:
1. Ask the agent a question
2. Quit
Enter your choice (1 or 2):
```

## Troubleshooting

### Common Issues

| Issue | Solution |
|-------|----------|
| Missing OPENAI_API_KEY | Ensure the environment variable is set before running |
| npx not found | Install Node.js or run `npm install -g npx` |
| MCP server connection failure | Check internet connection for Context7; verify npx works locally |
| Import errors | Reinstall Python packages with `pip install --upgrade` |

### Verification Commands

Test your installation by checking each component:

```bash
# Verify Python packages
python -c "import langchain_mcp_adapters; import langgraph; import langchain_openai"

# Verify npx is available
npx --version

# Verify Python version
python --version
```

## Project Dependencies Flow

```mermaid
graph LR
    A[main.py] --> B[langchain_mcp_adapters<br/>MultiServerMCPClient]
    A --> C[langgraph<br/>create_react_agent]
    A --> D[langchain_openai<br/>ChatOpenAI]
    A --> E[langgraph.checkpoint.memory<br/>InMemorySaver]
    B --> F[Context7 MCP]
    B --> G[MetMuseum MCP]
```

资料来源：[main.py](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

## Next Steps

After successful installation, refer to the following:

1. **Usage Guide** - How to interact with the agent
2. **Architecture Overview** - Understanding the multi-server MCP client design
3. **MCP Server Documentation** - Details on Context7 and MetMuseum capabilities

## System Requirements Summary

| Component | Specification |
|-----------|---------------|
| OS | Cross-platform (Windows, macOS, Linux) |
| Memory | 4GB minimum recommended |
| Disk Space | 500MB for dependencies |
| Network | Required for Context7 server and OpenAI API access |

---

<a id='page-configuration'></a>

## Configuration

### 相关页面

相关主题：[Installation Guide](#page-installation)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [main.py](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)
- [README.md](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/README.md)
</details>

# Configuration

This document describes the configuration system for the mcp-ai-agent project, covering all configurable components including MCP servers, language models, memory systems, and agent behavior.

## Overview

The mcp-ai-agent uses a multi-server Model Context Protocol (MCP) architecture that requires configuration for:

- MCP server connections (transport protocols, endpoints)
- Language model integration (OpenAI API)
- Conversation memory persistence
- Agent execution parameters

资料来源：[README.md](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/README.md)

## MCP Server Configuration

The agent connects to multiple MCP servers simultaneously using the `MultiServerMCPClient` from `langchain-mcp-adapters`. Each server defines its own transport protocol and connection parameters.

资料来源：[main.py:26-40](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

### Configuration Structure

```python
client = MultiServerMCPClient({
    "context7": {
        "url": "https://mcp.context7.com/mcp",
        "transport": "streamable_http",
    },
    "met-museum": {
        "command": "npx",
        "args": ["-y", "metmuseum-mcp"],
        "transport": "stdio",
    }
})
```

### Supported Transport Protocols

| Transport | Use Case | Configuration Required |
|-----------|----------|------------------------|
| `streamable_http` | Remote/cloud servers | `url` endpoint |
| `stdio` | Local/npx-based servers | `command` and `args` |

资料来源：[README.md](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/README.md)

### Context7 Server Configuration

| Parameter | Value | Description |
|-----------|-------|-------------|
| Server Name | `context7` | Identifier for the MCP server |
| URL | `https://mcp.context7.com/mcp` | Remote endpoint for library documentation |
| Transport | `streamable_http` | HTTP-based streaming protocol |
| Capabilities | LLM-optimized docs search across major frameworks | Provides access to code library documentation |

资料来源：[main.py:28-30](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

### MetMuseum Server Configuration

| Parameter | Value | Description |
|-----------|-------|-------------|
| Server Name | `met-museum` | Identifier for the MCP server |
| Command | `npx` | Node.js package runner |
| Args | `["-y", "metmuseum-mcp"]` | Auto-install and execute the museum MCP package |
| Transport | `stdio` | Standard input/output communication |
| Capabilities | Access to 400,000+ Metropolitan Museum artworks | Provides art collection metadata and images |

资料来源：[main.py:31-35](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/README.md)

## Language Model Configuration

The agent uses OpenAI's GPT-5 Nano model for reasoning and natural language generation.

### OpenAI Model Initialization

```python
openai_model = ChatOpenAI(
    model="gpt-5-nano",
)
```

| Parameter | Value | Description |
|-----------|-------|-------------|
| Model | `gpt-5-nano` | OpenAI's lightweight reasoning engine |
| Integration | `langchain_openai.ChatOpenAI` | LangChain wrapper for OpenAI API |

资料来源：[main.py:42-44](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

### API Key Configuration

The OpenAI API key must be set as an environment variable before running the agent:

```bash
export OPENAI_API_KEY="your-api-key-here"
```

资料来源：[README.md](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/README.md)

## Memory Configuration

The agent implements persistent conversation memory using LangGraph's `InMemorySaver` checkpointer.

### Checkpointer Setup

```python
checkpointer = InMemorySaver()
```

| Component | Class | Purpose |
|-----------|-------|---------|
| Memory | `InMemorySaver` | Stores conversation history in memory |
| Persistence | Thread-based | Messages grouped by `thread_id` |

资料来源：[main.py:47-48](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

### Thread Configuration

```python
config = {"configurable": {"thread_id": "conversation_id"}}
```

| Parameter | Value | Description |
|-----------|-------|-------------|
| Thread ID | `"conversation_id"` | Groups all messages in the current session |
| Scope | Session-level | Maintains context across all agent interactions |

资料来源：[main.py:50-51](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

## Agent Configuration

The ReAct (Reasoning + Acting) agent is created using LangGraph's `create_react_agent` factory function.

### Agent Creation

```python
agent = create_react_agent(
    model=openai_model,
    tools=tools,
    checkpointer=checkpointer
)
```

| Parameter | Source | Description |
|-----------|--------|-------------|
| `model` | `ChatOpenAI` instance | GPT-5 Nano for reasoning |
| `tools` | `MultiServerMCPClient.get_tools()` | All tools from both MCP servers |
| `checkpointer` | `InMemorySaver` instance | Conversation memory |

资料来源：[main.py:53-57](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

## System Prompt Configuration

The agent's behavior is defined through a system message passed during the initial invocation.

### Default System Message

```python
{"role": "system", "content": "You are a smart, useful agent with tools to access code library documentation and the Met Museum collection."}
```

| Field | Value | Purpose |
|-------|-------|---------|
| Role | `system` | Defines agent persona |
| Content | Agent description | Instructs agent about available capabilities |

资料来源：[main.py:67](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

## Configuration Flow

```mermaid
graph TD
    A[Configuration Start] --> B[MCP Server Config]
    B --> C[MultiServerMCPClient]
    C --> D[Context7 HTTP]
    C --> E[MetMuseum STDIO]
    D --> F[Get Tools]
    E --> F
    F --> G[LLM Config]
    G --> H[ChatOpenAI gpt-5-nano]
    H --> I[Memory Config]
    I --> J[InMemorySaver]
    J --> K[Agent Config]
    K --> L[create_react_agent]
    L --> M[Ready for Invocation]
```

## Runtime Configuration

### Asynchronous Execution

The application runs using Python's `asyncio` event loop:

```python
async def main():
    # All configuration and agent operations
    pass

if __name__ == "__main__":
    asyncio.run(main())
```

### Agent Invocation

Each user interaction passes through the configured thread:

```python
response = await agent.ainvoke(
    {"messages": query},
    config=config  # Contains thread_id for memory persistence
)
```

资料来源：[main.py:80-87](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/main.py)

## Configuration Dependencies

```mermaid
graph LR
    A[main.py] --> B[langchain_mcp_adapters.client]
    A --> C[langgraph.prebuilt]
    A --> D[langgraph.checkpoint.memory]
    A --> E[langchain_openai]
    B --> F[MultiServerMCPClient]
    C --> G[create_react_agent]
    D --> H[InMemorySaver]
    E --> I[ChatOpenAI]
```

## Environment Requirements

| Requirement | Version | Purpose |
|-------------|---------|---------|
| Python | 3.10+ | Runtime environment |
| Node.js/npx | Latest | Required for MetMuseum STDIO server |
| OpenAI API Key | Valid key | LLM access |

### Required Python Packages

```bash
pip install langchain-mcp-adapters langgraph langchain-openai
```

### Required npm Packages

```bash
npm install -g npx
```

资料来源：[README.md](https://github.com/LeelaissakAttota/mcp-ai-agent/blob/main/README.md)

## Configuration Summary Table

| Component | Class/Function | Key Parameter | Location |
|-----------|----------------|---------------|----------|
| MCP Client | `MultiServerMCPClient` | Transport definitions | main.py:26-40 |
| Context7 | HTTP config | URL endpoint | main.py:28-30 |
| MetMuseum | STDIO config | npx command | main.py:31-35 |
| LLM | `ChatOpenAI` | model="gpt-5-nano" | main.py:42-44 |
| Memory | `InMemorySaver` | In-memory storage | main.py:47-48 |
| Thread | Dict config | thread_id | main.py:50-51 |
| Agent | `create_react_agent` | model + tools + checkpointer | main.py:53-57 |

## See Also

- [Installation Guide](README.md#-how-to-run) - Setup instructions
- [Architecture Overview](README.md#-architecture) - System design
- [MCP Servers](README.md#-integrated-mcp-servers) - Available tool providers

---

---

## Doramagic 踩坑日志

项目：LeelaissakAttota/mcp-ai-agent

摘要：发现 7 个潜在踩坑项，其中 0 个为 high/blocking；最高优先级：身份坑 - 仓库名和安装名不一致。

## 1. 身份坑 · 仓库名和安装名不一致

- 严重度：medium
- 证据强度：runtime_trace
- 发现：仓库名 `mcp-ai-agent` 与安装入口 `metmuseum-mcp` 不完全一致。
- 对用户的影响：用户照着仓库名搜索包或照着包名找仓库时容易走错入口。
- 建议检查：在 npm/PyPI/GitHub 上确认包名映射和官方 README 说明。
- 复现命令：`npx metmuseum-mcp`
- 防护动作：页面必须同时展示 repo 名和真实安装入口，避免用户搜索错包。
- 证据：identity.distribution | github_repo:1158386431 | https://github.com/LeelaissakAttota/mcp-ai-agent | repo=mcp-ai-agent; install=metmuseum-mcp

## 2. 能力坑 · 能力判断依赖假设

- 严重度：medium
- 证据强度：source_linked
- 发现：README/documentation is current enough for a first validation pass.
- 对用户的影响：假设不成立时，用户拿不到承诺的能力。
- 建议检查：将假设转成下游验证清单。
- 防护动作：假设必须转成验证项；没有验证结果前不能写成事实。
- 证据：capability.assumptions | github_repo:1158386431 | https://github.com/LeelaissakAttota/mcp-ai-agent | README/documentation is current enough for a first validation pass.

## 3. 维护坑 · 维护活跃度未知

- 严重度：medium
- 证据强度：source_linked
- 发现：未记录 last_activity_observed。
- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。
- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。
- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。
- 证据：evidence.maintainer_signals | github_repo:1158386431 | https://github.com/LeelaissakAttota/mcp-ai-agent | last_activity_observed missing

## 4. 安全/权限坑 · 下游验证发现风险项

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：下游已经要求复核，不能在页面中弱化。
- 建议检查：进入安全/权限治理复核队列。
- 防护动作：下游风险存在时必须保持 review/recommendation 降级。
- 证据：downstream_validation.risk_items | github_repo:1158386431 | https://github.com/LeelaissakAttota/mcp-ai-agent | no_demo; severity=medium

## 5. 安全/权限坑 · 存在评分风险

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：风险会影响是否适合普通用户安装。
- 建议检查：把风险写入边界卡，并确认是否需要人工复核。
- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。
- 证据：risks.scoring_risks | github_repo:1158386431 | https://github.com/LeelaissakAttota/mcp-ai-agent | no_demo; severity=medium

## 6. 维护坑 · issue/PR 响应质量未知

- 严重度：low
- 证据强度：source_linked
- 发现：issue_or_pr_quality=unknown。
- 对用户的影响：用户无法判断遇到问题后是否有人维护。
- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。
- 防护动作：issue/PR 响应未知时，必须提示维护风险。
- 证据：evidence.maintainer_signals | github_repo:1158386431 | https://github.com/LeelaissakAttota/mcp-ai-agent | issue_or_pr_quality=unknown

## 7. 维护坑 · 发布节奏不明确

- 严重度：low
- 证据强度：source_linked
- 发现：release_recency=unknown。
- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。
- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。
- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。
- 证据：evidence.maintainer_signals | github_repo:1158386431 | https://github.com/LeelaissakAttota/mcp-ai-agent | release_recency=unknown

<!-- canonical_name: LeelaissakAttota/mcp-ai-agent; human_manual_source: deepwiki_human_wiki -->
