pydantic-resolve

MCP开发工具

提供方 allmonday · 包名 pydantic-resolve

开发工具 stdio · 本地进程 未标注 社区 / 第三方 Claude DesktopCursorClineClaude Code
查看接入方式

A universal data composition tool that generates JSON RPC, GraphQL, and even MCP.

一句话选型结论

按资料字段整理

pydantic-resolve 属于开发工具类 MCP 服务器,stdio · 本地进程,鉴权方式未标注,可直接接入 Claude Desktop、Cursor、Cline 等,有可直接执行的安装命令。接入前先确认权限范围;涉及写入、删除或付款的操作,建议先在测试环境验证。

分类开发工具 传输方式stdio · 本地进程 鉴权未标注 部署方式本地部署
GitHub 星标 319 仓库热度,无公开仓库时显示未标注
工具数 未标注 暴露给模型的工具数量
资源 / 提示词 0 / 0 资源与提示词模板数量
维护方 社区 / 第三方 核验等级 仅资料核对

工具与能力

开发工具
数量来自来源目录的标注,具体工具清单以官方文档为准
工具数量未标注暴露给模型可调用的工具个数
资源数量0可读取的资源条目
提示词数量0内置提示词模板数量

能力标签

pydantic-resolve bff fastapi fullstack graphql

支持客户端

适用场景

pydantic-resolvebfffastapi

安装与配置

stdio · 本地进程 未标注
客户端在本机拉起子进程,数据不出本机
pip install pydantic-resolve

这条命令只是入口,具体启动参数请按官方文档补齐,不要直接照搬到别的服务器。

  1. 1
    准备运行环境

    stdio 服务在本地起进程,需要先装好 Cross-platform,再按安装命令拉取依赖。

  2. 2
    安装服务

    复制上面的安装命令执行;命令里带占位符的位置,换成自己的密钥或路径。

  3. 3
    写入客户端配置

    在客户端的 MCP 配置里填好启动命令和参数,保存后完全退出客户端再打开,让新配置生效。

  4. 4
    验证是否可用

    连接成功后随便调一个只读工具,确认能返回结果,再接入正式流程。

典型使用场景

3 类
按分类与标签整理的常见用法,具体以官方文档为准
代码与仓库操作

在对话里直接查代码、提 issue、走 PR,省掉来回切工具。

本地命令与脚本

把构建、测试、格式化这类重复命令交给模型执行。

接口联调与测试

让模型调你的接口、跑一遍用例,快速定位问题。

选择建议

选之前先看这几条
按条目字段给出的判断,不替你决定用不用

值得选的地方

  • 有现成的安装命令,不用自己找入口,照着跑就能起服务。
  • 已适配 Claude Desktop、Cursor、Cline,换客户端不用重新研究配置。

先想清楚的地方

  • stdio 方式要求本地装好运行时(如 Node.js),换机器要重新装一遍。
  • 资料没标注工具数量,实际能力要装好后确认。
  • 版本更新与行为细节以官方仓库为准。

更适合

  • 需要在开发工具场景里让模型直接调用外部能力的人。
  • 已经在用 Claude Desktop、Cursor 的用户,接入路径最短。
  • 想先快速试一下、能接受在本地或自有环境跑服务的人。

不太适合

  • 完全不想在本地装环境的人。
  • 需要厂商级 SLA 和技术支持的生产环境。

同类对比

6 个同类
同分类里挑最接近的几条,字段以各自详情页为准
MCP 服务器工具数传输方式部署方式安装命令最后核验
pydantic-resolve当前 未标注 stdio · 本地进程 本地部署 有 2026-04-10
Git 838e2ec1 12 stdio · 本地进程 本地部署 有 2026-05-17
Markitdown MCP 2c653a5f 1 stdio · 本地进程 本地部署 有 2026-05-17
JavaGuide 未标注 stdio · 本地进程 本地部署 有 2026-04-11
awesome-claude-skills 未标注 stdio · 本地进程 本地部署 有 2026-04-26
Context7 831acf40 未标注 stdio · 本地进程 本地部署 有 2026-05-17

服务器档案

开发工具
字段来自项目仓库与公开索引,中文说明由本站标注
提供方allmonday上游标注的维护方 allmonday
分类开发工具本站按上游分类展示
连接方式stdio · 本地进程客户端在本机拉起子进程,数据不出本机
鉴权方式未标注远程服务建议用最小权限凭据
维护方社区 / 第三方核验等级 仅资料核对
包名 / 运行时pydantic-resolve · Cross-platform本地安装时用到的包标识与运行时
部署类型本地部署上游给出的部署形态
最近核验2026-04-10上游最后核验时间

详细介绍

19.4 KB
来自项目仓库与上游目录的原文,未做删改

Pydantic Resolve

> A progressive data-assembly framework for Python in Clean Architecture style — adopt each layer as you need it.

中文版

Requirements: Python 3.10+, Pydantic v2


TL;DR

pydantic-resolve is a complete framework for defining and assembling your data layer.

  • Define entities and relationships — Pydantic models + ER Diagram as the single source of truth.
  • Assemble response trees — resolve_* / post_* + batch loaders, recursive and N+1-safe.
  • Expose the same graph to REST, GraphQL, and AI agents (MCP) without rewriting.

These are progressive layers, not a package deal — most users stay on resolve_* and post_* forever, reach for ER Diagram only when relationships start repeating, and add GraphQL/MCP only when those surfaces are actually needed.```python
from typing import Optional
from pydantic import BaseModel
from pydantic_resolve import Loader, Resolver

class TaskView(BaseModel):
id: int
title: str
owner_id: int
owner: Optional[UserView] = None

def resolve_owner(self, loader=Loader(user_loader)):
    return loader.load(self.owner_id)

tasks = await Resolver().resolve(tasks) # one query, no N+1


The snippet above is the assembly step — describe what's missing, the framework fetches it. ER Diagram and GraphQL/MCP integrations build on top of the same model graph.

---

## The Problem

In most FastAPI projects, you define SQLAlchemy ORM models first, then create Pydantic schemas that mirror them. As the project grows, data-assembly logic ends up scattered across Repository / Service / Route:```python
@router.get("/tasks")
async def get_tasks():
    tasks = await task_service.get_tasks()
    user_ids = list({t.owner_id for t in tasks})
    users = await user_service.get_users_by_ids(user_ids)
    user_map = {u.id: u for u in users}
    return [
        TaskResponse(**{**t.model_dump(), 'owner': user_map.get(t.owner_id)})
        for t in tasks
    ]

This pattern couples your API contract to the database layout and gives business logic no stable home. pydantic-resolve provides that home. For the full architectural analysis, see Clean Architecture for Python.


Quick Start

Install```bash

pip install pydantic-resolve
pip install pydantic-resolve[mcp] # with MCP support


### The Example

Throughout the Quick Start, we build one API:

- `Sprint` has many `Task`
- `Task` has one `owner` (a `User`)
- The API also needs derived fields like `task_count` and `contributors`

Each step adds one concept on top of the previous code.

### Step 1: Load Related Data with `resolve_*`

Every response model has some fields already filled (from the database, from user input) and some fields that need to be fetched separately. `resolve_*` is how you declare those missing fields.```python
from typing import Optional

from pydantic import BaseModel
from pydantic_resolve import Loader, Resolver, build_object

class UserView(BaseModel):
    id: int
    name: str

async def user_loader(user_ids: list[int]):
    users = await db.query(User).filter(User.id.in_(user_ids)).all()
    return build_object(users, user_ids, lambda user: user.id)

class TaskView(BaseModel):
    id: int
    title: str
    owner_id: int
    owner: Optional[UserView] = None

    def resolve_owner(self, loader=Loader(user_loader)):
        return loader.load(self.owner_id)

tasks = [TaskView.model_validate(task) for task in raw_tasks]
tasks = await Resolver().resolve(tasks)

A useful mental model: resolve_* means "this field needs data from outside the current node." The framework collects every loader.load(...) call across the tree, batches one query per loader, and maps the results back.

Step 2: Compose Nested Trees

Real APIs rarely have just one relationship. When Sprint contains many Tasks, and each Task already knows how to load its owner, the resolver walks the tree and batch-loads everything recursively.```python
from typing import List

from pydantic_resolve import build_list

async def task_loader(sprint_ids: list[int]):
tasks = await db.query(Task).filter(Task.sprint_id.in_(sprint_ids)).all()
return build_list(tasks, sprint_ids, lambda task: task.sprint_id)

class SprintView(BaseModel):
id: int
name: str
tasks: List[TaskView] = []

def resolve_tasks(self, loader=Loader(task_loader)):
    return loader.load(self.id)

sprints = [SprintView.model_validate(sprint) for sprint in raw_sprints]
sprints = await Resolver().resolve(sprints)


**Result:** one query per loader, regardless of how many sprints or tasks you load.

### Step 3: Compute Derived Fields with `post_*`

`task_count` and `contributor_names` don't come from a query — they're derived from data already on the model. `post_*` handles these: it runs **after** all nested `resolve_*` calls have finished.```python
class SprintView(BaseModel):
    id: int
    name: str
    tasks: List[TaskView] = []
    task_count: int = 0
    contributor_names: list[str] = []

    def resolve_tasks(self, loader=Loader(task_loader)):
        return loader.load(self.id)

    def post_task_count(self):
        return len(self.tasks)

    def post_contributor_names(self):
        return sorted({task.owner.name for task in self.tasks if task.owner})

Execution order:

  1. resolve_tasks loads the sprint's tasks.
  2. Each TaskView.resolve_owner loads its owner.
  3. post_task_count and post_contributor_names run after those nested fields are ready.

Putting it all together, the response looks like:```json
{
"id": 1,
"name": "Sprint 1",
"tasks": [
{
"id": 101,
"title": "Implement login",
"owner_id": 1,
"owner": { "id": 1, "name": "Alice" }
}
],
"task_count": 1,
"contributor_names": ["Alice"]
}


| | `resolve_*` | `post_*` |
|---|---|---|
| Needs external IO? | Yes | Usually no |
| Runs before descendants ready? | Yes | No |
| Good for counts, sums, formatting? | Sometimes | Yes |
| Return value resolved again? | Yes | No |

These two patterns cover most API endpoints. The next section covers cross-tree coordination — skip it if your tree is simple enough with `resolve_*` and `post_*`.

### Step 4: Coordinate Parent and Child *(optional)*

When parent and child nodes need to share data without hard-coding references to each other, two helpers cover the two directions.

#### 4a. ExposeAs — parent → child

Send a value from an ancestor down to its descendants.```python
from typing import Annotated

from pydantic_resolve import ExposeAs

class SprintView(BaseModel):
    id: int
    name: Annotated[str, ExposeAs('sprint_name')]  # visible to all descendants
    tasks: List[TaskView] = []

    def resolve_tasks(self, loader=Loader(task_loader)):
        return loader.load(self.id)

class TaskView(BaseModel):
    id: int
    title: str
    owner_id: int
    owner: Optional[UserView] = None
    full_title: str = ""

    def resolve_owner(self, loader=Loader(user_loader)):
        return loader.load(self.owner_id)

    def post_full_title(self, ancestor_context):
        return f"{ancestor_context['sprint_name']} / {self.title}"

Use this when a child needs context from an ancestor (sprint name, permissions, locale).

4b. SendTo + Collector — child → parent

Aggregate values from many descendants up to one ancestor.```python
from typing import Annotated

from pydantic_resolve import Collector, SendTo

class SprintView(BaseModel):
id: int
name: str
tasks: List[TaskView] = []
contributors: list[UserView] = []

def resolve_tasks(self, loader=Loader(task_loader)):
    return loader.load(self.id)

def post_contributors(self, collector=Collector('contributors')):
    return collector.values()

class TaskView(BaseModel):
id: int
title: str
owner_id: int
owner: Annotated[Optional[UserView], SendTo('contributors')] = None

def resolve_owner(self, loader=Loader(user_loader)):
    return loader.load(self.owner_id)

Use this when a parent needs to aggregate values from many descendants (all contributors, all tags, all attachments).

---

## How It Works

Three mechanisms cover the whole library:

| What you need | What you write | What the framework does |
|------|----------------|-------------------------|
| Load related data | `resolve_*` + `Loader(...)` | Batch lookups and map results back |
| Compute derived fields | `post_*` | Run after descendants are fully resolved |
| Reuse relationship declarations | ER Diagram + `AutoLoad` (see below) | Centralize relationship wiring for many models |
```mermaid
flowchart LR
    subgraph FW["Frameworks & Interfaces"]
        R["Response<br/>FastAPI routes"]
    end
    subgraph APP["Application Business Rules"]
        RV["Resolver<br/>resolve / post"]
    end
    subgraph ENT["Enterprise Business Rules"]
        E["Entity + ER Diagram"]
    end
    subgraph ADP["Interface Adapters"]
        L["Loader"]
    end
    FW --> APP --> ENT --> ADP

The dependency direction always points inward: Entity doesn't know about Loader. Loader doesn't know about FastAPI. FastAPI doesn't know about the database.


Clean Architecture Mapping

pydantic-resolve is built around Clean Architecture. Its components map 1:1 to the layers:

Clean Architecture Layer pydantic-resolve Component
Enterprise Business Rules Entity + ER Diagram
Application Business Rules Resolver + resolve/post
Interface Adapters Loader (data access)
Frameworks & Interfaces FastAPI routes + GraphQL + MCP

This mapping is what makes the library more than a DataLoader helper — it gives data assembly a stable home that survives framework churn.

For the full architectural analysis, see Clean Architecture for Python.


Going Further: ER Diagram + AutoLoad

> Optional. The Core API above (resolve_* / post_* + Loader) covers most use cases. Read this section only when you notice the same relationship being declared repeatedly across response models.

A common signal is when you see the same relation described again and again:

  • TaskCard.resolve_owner
  • TaskDetail.resolve_owner
  • SprintBoard.resolve_tasks
  • SprintReport.resolve_tasks

At that point, the problem is no longer "how do I load this field?" but "where is the source of truth for relationships?" ER Diagram + AutoLoad is the answer.

Cost vs Benefit

Question Hand-written Core API ER Diagram + AutoLoad
First endpoint Faster Slower
Upfront setup Low Medium
Reusing the same relation in many models Repetitive Centralized
Changing a relationship later Update many resolve_* methods Update one ERD declaration
GraphQL / MCP generation Separate work Natural extension

ERD mode asks for more discipline up front:

  • Define entity classes.
  • Declare relationships explicitly.
  • Create AutoLoad from the same diagram used by the resolver.

That setup cost is real. The payoff is that relationship knowledge converges into one place — every Response is just a different view of the same Entity graph. The same ERD also powers GraphQL queries, MCP services, and admin tools.

The Same Example in ERD Mode```python

from typing import Optional

from pydantic import BaseModel
from pydantic_resolve import Relationship, base_entity, config_global_resolver

BaseEntity = base_entity()

class UserEntity(BaseModel, BaseEntity):
id: int
name: str

class TaskEntity(BaseModel, BaseEntity):
relationships = [
Relationship(fk='owner_id', name='owner', target=UserEntity, loader=user_loader)
]
id: int
title: str
owner_id: int

class SprintEntity(BaseModel, BaseEntity):
relationships = [
Relationship(fk='id', name='tasks', target=list[TaskEntity], loader=task_loader)
]
id: int
name: str

diagram = BaseEntity.get_diagram()
AutoLoad = diagram.create_auto_load()
config_global_resolver(diagram)

class TaskView(TaskEntity):
# Field name matches Relationship(name='owner') → AutoLoad is implicit
owner: Optional[UserEntity] = None

class SprintView(SprintEntity):
# Field name matches Relationship(name='tasks') → AutoLoad is implicit
tasks: list[TaskView] = []
task_count: int = 0

def post_task_count(self):
    return len(self.tasks)

Compared with the Core API version:

- `resolve_owner` disappears.
- `resolve_tasks` disappears.
- The relationship definitions live in one place.
- `post_*` still works exactly the same.
- When a View field's name matches a relationship name, `Annotated[..., AutoLoad()]` is optional (implicit AutoLoad). Use the explicit form only when the field name differs from the relationship name.

If you want to hide internal FK fields such as `owner_id`, add `DefineSubset` on top of the ERD setup:```python
from pydantic_resolve import DefineSubset

class TaskSummary(DefineSubset):
    __subset__ = (TaskEntity, ('id', 'title'))
    owner: Optional[UserEntity] = None  # implicit AutoLoad

If Your ORM Already Knows the Relationships

Once ERD mode makes sense conceptually, you can let the ORM describe the relationships for you and import them into the Enterprise layer:```python
from pydantic_resolve import ErDiagram
from pydantic_resolve.integration.mapping import Mapping
from pydantic_resolve.integration.sqlalchemy import build_relationship

entities = build_relationship(
mappings=[
Mapping(entity=SprintEntity, orm=SprintORM),
Mapping(entity=TaskEntity, orm=TaskORM),
Mapping(entity=UserEntity, orm=UserORM),
],
session_factory=session_factory,
)

diagram = ErDiagram(entities=[]).add_relationship(entities)
AutoLoad = diagram.create_auto_load()
config_global_resolver(diagram)


`build_relationship` supports **SQLAlchemy**, **Django**, and **Tortoise ORM**. This is a good later optimization when your ORM metadata is already stable and you want to avoid duplicating relationship declarations.

---

## Adoption Path

### 1. Interface Adapters First

Start with `resolve_*` and `post_*` on one endpoint. You gain immediate N+1 protection without changing your architecture.

### 2. Enterprise Business Rules When Ready

When relationships start repeating across models, move them into ERD. This is the step where you establish your Enterprise layer.

### 3. Let the Framework Absorb ORM Metadata

When your ORM is stable, use `build_relationship()` to import existing relationship knowledge from the database layer.

**ERD mode is a good fit when:**

- The project has 3+ related entities reused across multiple response models.
- The team wants one shared place to inspect and discuss relationships.
- You want GraphQL or MCP generated from the same model graph.
- You want to hide FK fields while keeping relationship definitions centralized.

**Core API is usually enough when:**

- You only have a few loading requirements.
- You want each endpoint to stay maximally explicit.
- The response shape is still changing quickly.

→ Full ERD-Driven Guide

---

## Frameworks & Integrations

The library exposes your data through **two entry points** — ERD mode (data-model-first) and UseCase mode (operation-first). Both can power GraphQL, MCP, and admin tools:```mermaid
flowchart LR
    entity["Entity + ERD<br/>Enterprise Business Rules"]
    graphql["GraphQL"]
    usecase["UseCase Service<br/>business operations"]
    graphql_uc["GraphQL"]
    api["REST API"]
    mcp_uc["MCP Service"]
    mcp_gen["MCP Service"]

    entity --> graphql
    entity --> usecase
    usecase --> api
    usecase --> graphql_uc
    graphql_uc --> mcp_uc
    graphql --> mcp_gen

GraphQL — from ERD

Generate GraphQL schema from ERD and execute queries:```python
from pydantic_resolve.graphql import GraphQLHandler

handler = GraphQLHandler(diagram)
result = await handler.execute("{ users { id name posts { title } } }")

result.data == {"users": [{"id": 1, "name": "Alice", "posts": [{"title": "Hello"}]}, ...]}


→ GraphQL Documentation

### GraphQL — from UseCase Services

Compose GraphQL queries over `UseCaseService` classes — the API surface is a set of business operations, not a graph of entities:```python
from pydantic_resolve import query
from pydantic_resolve.use_case import UseCaseService
from pydantic_resolve.use_case.manager import UseCaseAppConfig, UseCaseManager

class UserService(UseCaseService):
    """User management."""

    @query
    async def list_users(cls) -> list[UserSummary]:
        """Get all users."""
        ...

manager = UseCaseManager(
    apps=[UseCaseAppConfig(name="blog", services=[UserService])]
)
app = manager.get_app("blog")
result = await app.compose("{ listUsers { id name } }")

Use this when the API is operation-first (RPC-style) rather than entity-graph-first.

MCP — from ERD

Expose GraphQL APIs to AI agents (requires pip install pydantic-resolve[mcp]):```python
from pydantic_resolve import AppConfig, create_mcp_server

mcp = create_mcp_server(apps=[AppConfig(name="blog", er_diagram=diagram)])
mcp.run()

Agents can then query: "list all posts by user Alice" → translated to GraphQL against your ERD


→ MCP Documentation

### MCP — from UseCase Services

Expose UseCase operations to AI agents via the same compose surface:```python
from pydantic_resolve.use_case import (
    UseCaseAppConfig,
    create_use_case_graphql_mcp_server,
)

mcp = create_use_case_graphql_mcp_server(
    apps=[UseCaseAppConfig(name="blog", services=[UserService, PostService])],
)
mcp.run()

The MCP server uses a 4-layer progressive disclosure (list_apps → describe_compose_schema → describe_compose_method → compose_query) so the agent can discover operations and shape queries without flooding its tool list.

Visualization

Interactive ERD exploration with fastapi-voyager:```python
from fastapi_voyager import create_voyager

app.mount('/voyager', create_voyager(app, er_diagram=diagram))
```


Comparisons

Entity-First (pydantic-resolve) vs ORM-First (traditional FastAPI)

Dimension ORM-First Entity-First
Type source of truth ORM model Entity (Pydantic)
Relationship wiring Repeated per endpoint Centralized in ERD
Data assembly Manual in Service/Route Automatic via Resolver
N+1 prevention Manual eager loading Built-in DataLoader batching
Multi-data source Scattered conversion code Unified Loader interface
API contract stability Tied to DB schema Independent of DB

pydantic-resolve vs GraphQL

Feature GraphQL pydantic-resolve
N+1 Prevention Manual DataLoader setup Built-in automatic batching
Type Safety Separate schema files Native Pydantic types
Learning Curve Steep (Schema, Resolvers, Loaders) Moderate (Loader/batch pattern required)
Debugging Complex introspection Standard Python debugging
Integration Requires dedicated server Works with any framework
Query Flexibility Any client can query anything Explicit API contracts

> Note: pydantic-resolve borrows the DataLoader batch pattern from GraphQL ecosystems but stays inside your existing REST framework. If you already use strawberry or ariadne and are happy with it, pydantic-resolve may be redundant for you.


Resources

  • Full Documentation
  • Clean Architecture for Python (full paper)
  • Example Project
  • Live Demo
  • Live Demo - GraphQL
  • API Reference

Credits

  • Faster Breadth-First GraphQL Execution — Shopify Engineering

License

MIT License

Author

tangkikodo (allmonday@126.com)

常见问题

8 问
答案由本站依据条目字段整理,不引用上游原文
pydantic-resolve 怎么安装?

在客户端按下面的安装命令接入:pip install pydantic-resolve。对应的包名是 pydantic-resolve。装完在客户端配置里引用同一个包或端点。

pydantic-resolve 怎么在 Claude Desktop、Cursor、Cline 里配置?

它的传输方式是stdio · 本地进程,在客户端的 MCP 配置里填好启动命令和参数,保存后完全退出客户端再打开,配置才会生效。

pydantic-resolve 收费吗?

本站不代收费用,也没有标注具体价格。是否收费取决于服务本身和背后的接口额度,正式使用前按官方说明确认。

pydantic-resolve 需要 API Key 吗?

资料没有标注鉴权方式,是否需要密钥取决于服务本身,接入前按官方文档确认。

pydantic-resolve 支持哪些客户端?

资料标注支持 Claude Desktop、Cursor、Cline、Claude Code;其他客户端只要能配置 MCP Server,也能用同样的命令或地址接入。

pydantic-resolve 能提供哪些能力?

资料显示能力标签包括 pydantic-resolve、bff、fastapi、fullstack、graphql。具体工具清单以官方文档为准。

pydantic-resolve 需要什么运行环境?

运行时为 Cross-platform;属于本地进程,需要在本机装好运行环境。

pydantic-resolve 是本地还是远程?

它是本地进程(stdio),由客户端在本机拉起。传输方式为stdio · 本地进程。

热门专题

按标签挑服务器
全部专题 →

服务器信息以作者仓库与官方文档为准;分类、传输方式与鉴权方式的中文说明为中文整理,最近核验 2026-04-10。