# Caselaw Mcp Server

> 法律案例检索与分析 MCP Server / FastAPI 服务，基于 cncases/cases 上游开源项目

- **Type:** MCP server
- **Install:** `agentstack add mcp-245678000000-caselaw-mcp-server`
- **Verified:** Yes — security-reviewed for prompt injection and unsafe behavior
- **Seller:** [245678000000](https://agentstack.voostack.com/s/245678000000)
- **Installs:** 0
- **Category:** [Integrations](https://agentstack.voostack.com/c/integrations)
- **Latest version:** 0.1.0
- **License:** MIT
- **Upstream author:** [245678000000](https://github.com/245678000000)
- **Source:** https://github.com/245678000000/caselaw-mcp-server

## Install

```sh
agentstack add mcp-245678000000-caselaw-mcp-server
```

Requires the [AgentStack CLI](https://agentstack.voostack.com/docs/cli). Works with Claude Code, Cursor, and any MCP-compatible agent.

## About

# CaseLaw MCP Server

法律案例检索与分析服务：提供 **标准 MCP（stdio）** 与 **FastAPI REST** 双入口，基于上游开源项目 [cncases/cases](https://github.com/cncases/cases) 的裁判文书检索能力，封装为 AI 可调用的工具层。

> **免责声明**：本项目仅供学习与研究，输出内容不构成法律意见。裁判文书数据的版权与使用合规由使用者自行负责。

## 功能

核心工具（REST 与 MCP 共用同一业务层，当前版本 **0.3.0**）：

| 工具 | 说明 |
|------|------|
| `search_cases` | 关键词 / 案号检索，可叠加法院、案由、类型、日期筛选 |
| `get_case_detail` | 获取案例详情（含全文） |
| `get_case_segments` | 文书分段（facts/opinion/result 或全文 chunk，控 token） |
| `summarize_case` | 生成结构化摘要 |
| `compare_cases` | 多案例对比（2–5 个，并行拉取 + 详情缓存） |
| `extract_rules` | 提取裁判规则 |

数据适配：

- **MockAdapter**（默认）：内置样例数据，开箱即用
- **CaseopenAdapter**：对接自建 [cncases/cases](https://github.com/cncases/cases) 实例

## 技术栈

- Python 3.11+
- FastAPI + Uvicorn（REST）
- [MCP Python SDK](https://github.com/modelcontextprotocol/python-sdk) FastMCP（stdio）
- Pydantic v2 + pydantic-settings
- httpx / BeautifulSoup4 + lxml

## 安装

```bash
git clone https://github.com/245678000000/caselaw-mcp-server.git
cd caselaw-mcp-server
python -m venv .venv
source .venv/bin/activate   # Windows: .venv\Scripts\activate
pip install -e ".[dev]"
cp .env.example .env        # 可选
```

## 快速开始（Mock）

### A. REST API

```bash
python run.py
# 或: caselaw-api
```

- 服务状态: http://127.0.0.1:5000/
- Swagger: http://127.0.0.1:5000/docs
- 健康检查: http://127.0.0.1:5000/health

示例：

```bash
curl "http://127.0.0.1:5000/api/v1/search?query=合同"
curl --get "http://127.0.0.1:5000/api/v1/search" --data-urlencode "case_number=(2023)京01民终1234号"
curl "http://127.0.0.1:5000/api/v1/search?query=合同&court=北京&case_type=民事"
curl "http://127.0.0.1:5000/api/v1/cases/1001"
curl "http://127.0.0.1:5000/api/v1/cases/1001/segments?max_chars=2000"
curl "http://127.0.0.1:5000/api/v1/cases/1001/segments?sections=facts,result"
```

### B. 标准 MCP（stdio）

```bash
python run_mcp.py
# 或: caselaw-mcp
```

进程通过 **stdio** 提供 Model Context Protocol，可被 Claude Desktop、Cursor 等客户端直接挂载。

#### Cursor / Claude Desktop 配置示例

将路径换成你本机仓库绝对路径：

```json
{
  "mcpServers": {
    "caselaw": {
      "command": "/absolute/path/to/caselaw-mcp-server/.venv/bin/python",
      "args": ["/absolute/path/to/caselaw-mcp-server/run_mcp.py"],
      "env": {
        "ADAPTER_TYPE": "mock"
      }
    }
  }
}
```

使用 caseopen 后端时：

```json
{
  "mcpServers": {
    "caselaw": {
      "command": "/absolute/path/to/caselaw-mcp-server/.venv/bin/python",
      "args": ["/absolute/path/to/caselaw-mcp-server/run_mcp.py"],
      "env": {
        "ADAPTER_TYPE": "caseopen",
        "CASEOPEN_BASE_URL": "http://127.0.0.1:8081"
      }
    }
  }
}
```

## 对接 caseopen（真实数据）

1. 按 [cncases/cases](https://github.com/cncases/cases) 说明自建检索服务（原始数据体量大，通常需要 **≥320GB** 磁盘，索引与转换可能耗时数小时）。
2. 配置环境变量后启动本服务：

```bash
export ADAPTER_TYPE=caseopen
export CASEOPEN_BASE_URL=http://127.0.0.1:8081
python run.py          # REST
# 或
python run_mcp.py      # MCP stdio
```

### Caseopen 能力与限制（请知悉）

- 上游以关键词 `search` 为主；**法院/案由/类型/日期为客户端 best-effort 过滤**（在导出窗口内过滤）。
- CSV 导出最多读取 `CASEOPEN_EXPORT_MAX_ROWS` 行（默认 2000），超出时响应 `truncated=true`，`total` 仅反映窗口内匹配数。
- 请求失败（超时 / 5xx / 网络错误）会按 `CASEOPEN_MAX_RETRIES` 重试。
- `/health` 的 `upstream_ok` 会探测 caseopen 是否可达。

## 环境变量

见 [`.env.example`](.env.example)：

| 变量 | 默认 | 说明 |
|------|------|------|
| `ADAPTER_TYPE` | `mock` | `mock` 或 `caseopen` |
| `CASEOPEN_BASE_URL` | `http://127.0.0.1:8081` | caseopen 实例地址 |
| `APP_HOST` | `0.0.0.0` | REST 监听地址 |
| `APP_PORT` | `5000` | REST 端口 |
| `LOG_LEVEL` | `INFO` | 日志级别 |
| `REQUEST_TIMEOUT` | `30.0` | 上游 HTTP 超时（秒） |
| `CASE_CACHE_SIZE` | `256` | 案例详情进程内 LRU 容量；`0` 关闭 |
| `CASEOPEN_MAX_RETRIES` | `2` | 上游失败重试次数 |
| `CASEOPEN_EXPORT_MAX_ROWS` | `2000` | CSV/HTML 导出最大行数 |
| `CASEOPEN_HEALTH_PATH` | `/` | 健康检查路径 |

## API 端点（REST）

| 方法 | 路径 | 说明 |
|------|------|------|
| GET | `/` | 服务状态 |
| GET | `/health` | 健康检查 |
| GET | `/docs` | Swagger |
| GET | `/api/v1/search` | 搜索（`query` 或 `case_number` + 可选筛选） |
| GET | `/api/v1/cases/{id}` | 案例详情 |
| GET | `/api/v1/cases/{id}/summary` | 摘要 |
| GET | `/api/v1/cases/{id}/segments` | 文书分段 |
| POST | `/api/v1/compare` | 对比 `{"case_ids":[...]}` |
| GET | `/api/v1/cases/{id}/rules` | 规则提取 |
| GET | `/mcp/v1/tools` | HTTP 工具清单（**历史兼容**） |
| POST | `/mcp/v1/tools/{name}` | HTTP 调用工具（**历史兼容**） |

### 关于 `/mcp/v1`

`/mcp/v1/*` 是早期自造的 HTTP 工具接口，**不是** [Model Context Protocol](https://modelcontextprotocol.io/) 的官方传输（stdio / Streamable HTTP / SSE）。  
请优先使用 **`caselaw-mcp` / `run_mcp.py`（stdio）** 对接 Agent 客户端。REST 业务 API 仍在 `/api/v1`。

## 架构

```
app/
├── main.py              # FastAPI 入口
├── mcp_server.py        # 标准 MCP（FastMCP + stdio）
├── factory.py           # 适配器 / CaseService 工厂
├── config.py            # 环境变量配置
├── adapters/            # mock | caseopen
├── routers/             # REST + legacy HTTP tools
├── schemas/
├── services/            # 搜索筛选、分段、摘要、对比、规则
└── utils/               # 日志、LRU 缓存、筛选辅助
run.py                   # REST 入口
run_mcp.py               # MCP stdio 入口
```

## 测试

```bash
ADAPTER_TYPE=mock python -m pytest tests/ -v
```

## License

MIT。上游 [cncases/cases](https://github.com/cncases/cases) 及其数据源另有各自许可与使用限制。

## Source & license

This open-source MCP server is cataloged on AgentStack and links to its original source — we do not rehost the code.

- **Author:** [245678000000](https://github.com/245678000000)
- **Source:** [245678000000/caselaw-mcp-server](https://github.com/245678000000/caselaw-mcp-server)
- **License:** MIT

Install and usage instructions live in the source repository linked above.

## Pricing

- **Free** — Free

## Security capabilities

Automated source analysis of v0.1.0 — what this tool can access:

- **Network access:** yes
- **Filesystem access:** no
- **Shell / process execution:** no
- **Environment & secrets:** yes
- **Dynamic code execution:** no

*"Yes" means the capability is present in the source — more access means more to trust, not that it is unsafe.*


## Versions

- **0.1.0** — security scan: passed — Imported from the upstream source.

## Links

- Listing page: https://agentstack.voostack.com/l/mcp-245678000000-caselaw-mcp-server
- Seller: https://agentstack.voostack.com/s/245678000000
- Browse the marketplace: https://agentstack.voostack.com/browse

---
Listed on AgentStack — the marketplace for AI agent skills and MCP servers. Every listing is security-reviewed. Creators keep 70%.
