Content
# PatentAgent
Intelligent patent analysis system driven by large language models (LLM). Engage in natural language conversations with patent data.
> Next-generation evolution of PatentSmelter. From "batch processing toolbox" to "conversational intelligent analysis".
> Recommended and only continuously maintained user entry: `frontend/` + `server.py`. The old mock frontend and Streamlit/Chainlit compatible entries are retained for migration only and do not represent current capabilities.
> Temporarily open-sourced in AGPL form. May be converted to a more permissive model in the future (no guarantee). Contact: 2507380208@wtu.edu.cn
<p align="center">
<img src="https://img.shields.io/badge/Python-3.10+-blue" alt="Python">
<img src="https://img.shields.io/badge/React-19-61dafb" alt="React">
<img src="https://img.shields.io/badge/FastAPI-0.115+-009688" alt="FastAPI">
<img src="https://img.shields.io/badge/Tools-16-orange" alt="Tools">
<img src="https://img.shields.io/badge/Version-3.0-lightgrey" alt="Version">
</p>
## Quick Start
### One-Click Launch (Recommended)
```bash
cd PatentAgent
bash start.sh
```
Automatically start the backend (FastAPI: 8000) and frontend (React: 5173), and the browser will open automatically.
### Separate Launches
**Backend:**
```bash
cd PatentAgent
MCP_INPUT_DIR=./my_patents PATENT_DATA_ROOT=./my_patents uvicorn server:app --host 127.0.0.1 --port 8000
# API Documentation: http://localhost:8000/docs
```
**Frontend:**
```bash
cd PatentAgent/frontend
npm install # First run
npm run dev # http://localhost:5173
```
### MCP Server
```bash
cd PatentAgent
pip install mcp
python mcp_server.py
```
Configure MCP connection in Claude Code / VS Code / Cursor. See [MCP User Guide](#mcp-user-guide).
## Core Features
- **Conversational Interaction** — Natural language questions, Agent understands intent, formulates plans, calls tools, and outputs conclusions
- **Dynamic Tool Directory** — Tool count registered in `/api/tools` as a single source, enabled or degraded by current field capabilities
- **Intelligent Keyword Filtering** — 400-word patent-specific stopword library + NLTK part-of-speech filtering, removing specification clichés and context noise
- **Result Traceability** — Charts, structured summaries, methods, field coverage, warnings, parameters, and time consumption uniformly returned
- **Native Visualization** — React/ECharts prioritize reading structured results, supporting original size, adaptive pane, full screen, PNG/JSON export, and data table switching
- **Multi-Vendor LLM** — Claude / OpenAI / DeepSeek, supporting local model privacy mode
- **Rapid Loading** — Multi-threaded parallel parsing + Pickle caching, first load 10s, cache hit 0.3s
- **Report Export** — HTML report (including complete Chinese typesetting), CSV data export
- **MCP Protocol Support** — Standard MCP (Model Context Protocol) stdio/HTTP server, Claude Code / VS Code / Cursor can directly call all tools
- **Algorithm Evidence Registry** — 16 tools registered with algorithm ID, version, formula, field threshold, paper source, and prohibited conclusions
## Tool List
| Tool | Description |
|------|-------------|
| `get_dataset_summary` | Dataset summary (total/time/IPC/top applicants) |
| `analyze_patent_trend` | Patent publication trend (monthly/annually, supporting IPC/applicant filtering) |
| `analyze_lifecycle` | Cumulative publication volume and year-over-year growth (no automatic lifecycle determination) |
| `analyze_ipc_distribution` | IPC classification heatmap (year × A-H department level) |
| `generate_wordcloud` | Keyword word cloud + word frequency histogram (including part-of-speech filtering) |
| `analyze_burst_terms` | Recent growth terms (minimum support, smoothing; not Kleinberg Burst) |
| `analyze_yearly_keywords` | Yearly keyword comparison (year × technical word heatmap) |
| `analyze_country_distribution` | First publication office distribution (not equivalent to market coverage) |
| `analyze_co_network` | Applicant cooperation network (interactive draggable) |
| `analyze_tech_roadmap` | Annual technical theme timeline (showing internal paths when citations are sufficient) |
| `analyze_tech_matrix` | Derwent abstract agent efficacy matrix + low co-occurrence review candidates |
| `analyze_clustering` | TF-IDF space K-means + silhouette select k + CC0.5 title |
| `analyze_patent_valuation` | Robust percentile value screening (not financial valuation) |
| `analyze_competitor_evolution` | IPC profile cosine shift / entropy / dominant share |
| `search_patents` | TF-IDF term similarity retrieval (not semantic embedding or full-text retrieval) |
| `read_patent_details` | Current data source record reading (Derwent abstract not complete specification) |
## MCP User Guide
PatentAgent provides a standard MCP server; available tool count subject to runtime registry, consistent with `/api/tools`.
### What is MCP
MCP is a standardized AI tool communication protocol. With it, AI clients are no longer limited to "just chatting" but can actively discover and call tools registered at runtime. AI clients can:
- Automatically discover available analysis tools
- Choose suitable tools based on user intent
- Call tools with parameters and obtain structured analysis results
- Write analysis conclusions based on real data
### Install MCP Dependencies
```bash
pip install mcp
```
### Start MCP Server
**stdio Mode (Recommended, for Claude Code / VS Code / Cursor):**
```bash
python mcp_server.py
```
Server communicates with client through standard input/output, no network port required.
**HTTP Mode (for remote access):**
```bash
python mcp_http_server.py --port 8000 --host 127.0.0.1
```
### Environment Variable Configuration
| Variable | Default Value | Description |
|------|---------------|-------------|
| `MCP_INPUT_DIR` | `./my_patents` | Patent data file directory |
| `MCP_STORE_CACHE_TTL` | `300` | Data cache expiration (seconds), automatically reload from disk on timeout |
| `MCP_LOG_LEVEL` | `INFO` | Log level: DEBUG / INFO / WARNING / ERROR |
| `MCP_HTTP_PORT` | `8000` | HTTP mode listening port |
| `MCP_HTTP_HOST` | `127.0.0.1` | HTTP mode listening address |
| `MCP_MAX_ITEMS_IN_RESULT` | `50` | Maximum items in list fields of analysis results |
### Configure Claude Code
Create or edit `.mcp.json` in the project root directory:
```json
{
"mcpServers": {
"patent-agent": {
"command": "python3",
"args": ["/absolute/path/PatentAgent/mcp_server.py"],
"env": {
"MCP_INPUT_DIR": "/absolute/path/my_patents",
"MCP_LOG_LEVEL": "WARNING"
}
}
}
}
```
Restart Claude Code, and the MCP server will start automatically. You can directly say:
- "List available patent analysis tools"
- "Give me a dataset summary"
- "Analyze publication trends from 2018 to 2022"
- "Find technology gaps, which directions have no patent layout yet"
- "Show technology hotspots with a word cloud"
### Configure VS Code / Cursor
Create `.vscode/mcp.json` in the project root directory:
```json
{
"servers": {
"patent-agent": {
"type": "stdio",
"command": "python3",
"args": ["/absolute/path/PatentAgent/mcp_server.py"],
"env": {
"MCP_INPUT_DIR": "/absolute/path/my_patents",
"MCP_LOG_LEVEL": "WARNING"
}
}
}
}
```
### MCP Tool List
MCP server exposes tool interfaces (tool count subject to runtime registry):
| Tool Name | Parameters | Description |
|-----------|------------|-------------|
| `get_dataset_summary` | None | Dataset summary (total/time/IPC/top applicants) |
| `analyze_patent_trend` | `chart_type`, `year_start`, `year_end`, `ipc_filter`, `applicant_filter` | Publication trend analysis |
| `analyze_lifecycle` | None | Cumulative publication volume and year-over-year growth (no lifecycle determination) |
| `analyze_ipc_distribution` | None | IPC classification heatmap |
| `generate_wordcloud` | `text_source` | Keyword word cloud + word frequency histogram |
| `analyze_burst_terms` | None | Technology burst term detection |
| `analyze_yearly_keywords` | `text_source` | Yearly keyword comparison |
| `analyze_country_distribution` | None | First publication office distribution (not family market coverage) |
| `analyze_co_network` | None | Applicant cooperation network |
| `analyze_tech_roadmap` | `top_n_per_year` | Technology roadmap |
| `analyze_tech_matrix` | `top_n` | Derwent abstract agent efficacy matrix + low co-occurrence review candidates |
| `analyze_clustering` | `n_clusters` | Patent text clustering |
| `analyze_patent_valuation` | `top_n`, `citation_mode` | Value screening (not financial valuation) |
| `analyze_competitor_evolution` | `top_n_applicants` | IPC profile engineering metrics (not PatentMiner DICT) |
| `search_patents` | `query`, `top_k`, `year_start`, `year_end` | TF-IDF term retrieval |
| `read_patent_details` | `patent_numbers` (up to 5) | Current data source field reading |
### Analysis Result Format
MCP tool calls return two content types:
- **`text`** — Structured JSON data, containing main analysis result data (e.g., trend data points, word frequency lists, matrix values)
- **`resource`** (optional) — Embedded HTML charts (text/html MIME), client-side rendering as interactive pyecharts charts
### Verify MCP Server
You can use a Python script to verify if the MCP server is working correctly:
```bash
python -m pytest tests/test_mcp_integration.py -v
```
Test coverage: server initialization, dynamic tool list, tool calls, error handling.
## Architecture
```
React Frontend (Vite + TypeScript) | MCP Server (stdio/HTTP)
↕ HTTP + SSE ↕ JSON-RPC
FastAPI Backend (server.py)
↕
Agent Orchestration Layer (conditions/dependencies/retries + complete evidence block synthesis + SQLite persistent sessions)
↕
Tool Layer (registry as single source, including capability access control and unified result contract)
↕
Engine Layer (pure computation)
↕
Data Access Layer (Parquet cache + column projection)
↕
Knowledge Layer (16 tool algorithm evidence registry + decision templates)
```
## Project Structure
```
PatentAgent/
├── server.py # FastAPI backend (REST, session management, and SSE streaming)
├── start.sh # One-click launch script
├── frontend/ # React frontend
│ ├── src/
│ │ ├── App.tsx # Main application (three-column layout)
│ │ ├── api.ts # All API calls + SSE streaming
│ │ ├── types.ts # TypeScript type definitions
│ │ └── components/ # Native ECharts registry, compatible ChartFrame, tool cards, and message components
│ └── package.json
├── agent/ # Agent orchestration layer
│ ├── orchestrator.py # State machine + tool orchestration
│ ├── strategy_chains.py # Old version compatible, no longer called by web main process
│ ├── cross_tool_synthesis.py # Cross-tool association reasoning
│ ├── recommendation_engine.py # Strategic suggestion generation
│ ├── adaptive_planner.py # Old version compatible, no automatic tool appending
│ ├── proactive_discovery.py # Proactive discovery engine
├── storage/conversation_store.py # Session, turn, and structured evidence (no API key/chart HTML saved)
│ └── prompts.py
├── tools/ # Tool layer (16 runtime-registered tools)
├── engine/ # Analysis engine layer (13 pure computation modules)
├── patent_mcp/ # MCP server
├── mcp_server.py # MCP stdio entry
├── models/ # Pydantic data models
├── knowledge/ # Single algorithm evidence registry + decision templates
├── storage/ # Data access layer
├── viz/ # Old client/MCP pyecharts compatible visualization layer
└── tests/ # Python regression tests + frontend rendering tests
```
## Configuration
### LLM Settings
```
Claude API → Long context + tool calls most mature (recommended)
OpenAI API → Widest compatibility
DeepSeek API → Best Chinese price-performance ratio, supporting direct domestic access
Default model: Claude `claude-sonnet-4-6` / OpenAI `gpt-4.1` /
DeepSeek `deepseek-v4-flash`
Local privacy mode: vLLM + Qwen3-32B / DeepSeek-V3 + BGE-M3 Embedding
```
Connection check not only tests a single text response but also completes a side-effect-free
`tool_calls → local result return → final text`, and verifies a structured JSON output. Only if all pass, the frontend displays
“LLM tool calls ready”.
Web Agent's normal process directly selects the minimal necessary tool set by LLM in the first round, local parameter/data/
cost access control passed, then executes, and returns results according to OpenAI, Claude, or DeepSeek's official message protocol.
In the second round, new tools are disabled, and a structured answer and dynamic follow-up questions are generated.
You can also configure service providers like Openrouter in the web interface. I strive to reduce software usage barriers. Users are suggested to use Deepseek as the default model, which significantly reduces usage costs.
### Data Format
Supports Web of Science (Clarivate Derwent) patent export `.txt` files.
Place files in `my_patents/` directory, load in GUI. Supports incremental updates, cache automatically invalidates.
## Documentation
- [Project and Paper Audit](docs/project-audit.md) — Data quality, paper applicability conditions, advantages/weaknesses, and legal boundaries
- [16 Tool Algorithm Evidence Matrix](docs/tool-evidence-matrix.md) — Automatically generated from `knowledge/tool_evidence.json`
- DII benchmark data status — Retrieval, authorization verification, and import audit methods (provided with patent data directory, not included in source code repository)
- [Software Manual](软件说明书.txt) — Architecture design, functional details, technical stack, version history
- [Operation Guide](操作指南.txt) — Step-by-step tutorial from scratch, including environment configuration, tool usage, and FAQs
MCP Config
Below is the configuration for this MCP Server. You can copy it directly to Cursor or other MCP clients.
mcp.json
Connection Info
You Might Also Like
No recommendations available