strawberry-orm 0.24.2__tar.gz → 0.25.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {strawberry_orm-0.24.2 → strawberry_orm-0.25.0}/PKG-INFO +105 -57
- {strawberry_orm-0.24.2 → strawberry_orm-0.25.0}/README.md +101 -56
- {strawberry_orm-0.24.2 → strawberry_orm-0.25.0}/pyproject.toml +5 -1
- {strawberry_orm-0.24.2 → strawberry_orm-0.25.0}/pyproject.toml.orig +2 -1
- {strawberry_orm-0.24.2 → strawberry_orm-0.25.0}/src/strawberry_orm/backends/_base.py +306 -31
- {strawberry_orm-0.24.2 → strawberry_orm-0.25.0}/src/strawberry_orm/backends/django.py +7 -3
- {strawberry_orm-0.24.2 → strawberry_orm-0.25.0}/src/strawberry_orm/backends/protocol.py +3 -1
- {strawberry_orm-0.24.2 → strawberry_orm-0.25.0}/src/strawberry_orm/backends/sqlalchemy.py +9 -3
- {strawberry_orm-0.24.2 → strawberry_orm-0.25.0}/src/strawberry_orm/backends/tortoise.py +14 -6
- {strawberry_orm-0.24.2 → strawberry_orm-0.25.0}/src/strawberry_orm/batching.py +123 -45
- strawberry_orm-0.25.0/src/strawberry_orm/contrib/__init__.py +5 -0
- strawberry_orm-0.25.0/src/strawberry_orm/contrib/mcp/__init__.py +22 -0
- strawberry_orm-0.25.0/src/strawberry_orm/contrib/mcp/agent.py +502 -0
- strawberry_orm-0.25.0/src/strawberry_orm/contrib/mcp/checks.py +119 -0
- strawberry_orm-0.25.0/src/strawberry_orm/contrib/mcp/clarification.py +147 -0
- strawberry_orm-0.25.0/src/strawberry_orm/contrib/mcp/server.py +159 -0
- {strawberry_orm-0.24.2 → strawberry_orm-0.25.0}/src/strawberry_orm/core.py +39 -8
- strawberry_orm-0.25.0/src/strawberry_orm/cover.py +88 -0
- {strawberry_orm-0.24.2 → strawberry_orm-0.25.0}/src/strawberry_orm/relay/connection.py +50 -40
- {strawberry_orm-0.24.2 → strawberry_orm-0.25.0}/src/strawberry_orm/__init__.py +0 -0
- {strawberry_orm-0.24.2 → strawberry_orm-0.25.0}/src/strawberry_orm/_async.py +0 -0
- {strawberry_orm-0.24.2 → strawberry_orm-0.25.0}/src/strawberry_orm/backends/__init__.py +0 -0
- {strawberry_orm-0.24.2 → strawberry_orm-0.25.0}/src/strawberry_orm/backends/filter_pk_shortcut.py +0 -0
- {strawberry_orm-0.24.2 → strawberry_orm-0.25.0}/src/strawberry_orm/fields.py +0 -0
- {strawberry_orm-0.24.2 → strawberry_orm-0.25.0}/src/strawberry_orm/filters.py +0 -0
- {strawberry_orm-0.24.2 → strawberry_orm-0.25.0}/src/strawberry_orm/lazy_resolution.py +0 -0
- {strawberry_orm-0.24.2 → strawberry_orm-0.25.0}/src/strawberry_orm/mutations.py +0 -0
- {strawberry_orm-0.24.2 → strawberry_orm-0.25.0}/src/strawberry_orm/optimizer/__init__.py +0 -0
- {strawberry_orm-0.24.2 → strawberry_orm-0.25.0}/src/strawberry_orm/optimizer/extension.py +0 -0
- {strawberry_orm-0.24.2 → strawberry_orm-0.25.0}/src/strawberry_orm/optimizer/selections.py +0 -0
- {strawberry_orm-0.24.2 → strawberry_orm-0.25.0}/src/strawberry_orm/optimizer/store.py +0 -0
- {strawberry_orm-0.24.2 → strawberry_orm-0.25.0}/src/strawberry_orm/payload.py +0 -0
- {strawberry_orm-0.24.2 → strawberry_orm-0.25.0}/src/strawberry_orm/policy.py +0 -0
- {strawberry_orm-0.24.2 → strawberry_orm-0.25.0}/src/strawberry_orm/py.typed +0 -0
- {strawberry_orm-0.24.2 → strawberry_orm-0.25.0}/src/strawberry_orm/relay/__init__.py +0 -0
- {strawberry_orm-0.24.2 → strawberry_orm-0.25.0}/src/strawberry_orm/repo.py +0 -0
- {strawberry_orm-0.24.2 → strawberry_orm-0.25.0}/src/strawberry_orm/tags.py +0 -0
- {strawberry_orm-0.24.2 → strawberry_orm-0.25.0}/src/strawberry_orm/types.py +0 -0
- {strawberry_orm-0.24.2 → strawberry_orm-0.25.0}/src/strawberry_orm/upserts.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: strawberry-orm
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.25.0
|
|
4
4
|
Summary: Unified, backend-agnostic ORM abstraction for Strawberry GraphQL
|
|
5
5
|
Author: James Davidson, Patrick Arminio
|
|
6
6
|
Author-email: James Davidson <jamie.t.davidson@gmail.com>, Patrick Arminio <patrick.arminio@gmail.com>
|
|
@@ -14,6 +14,8 @@ Classifier: Programming Language :: Python :: 3.13
|
|
|
14
14
|
Classifier: Programming Language :: Python :: 3.14
|
|
15
15
|
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
16
16
|
Requires-Dist: strawberry-graphql>=0.311.0
|
|
17
|
+
Requires-Dist: mcp>=2.3.0 ; extra == 'contrib-mcp'
|
|
18
|
+
Requires-Dist: any-llm-sdk>=1.40.1 ; extra == 'contrib-mcp'
|
|
17
19
|
Requires-Dist: greenlet>=3.3.2 ; extra == 'dev'
|
|
18
20
|
Requires-Dist: pytest>=8.0 ; extra == 'dev'
|
|
19
21
|
Requires-Dist: pytest-asyncio>=0.24 ; extra == 'dev'
|
|
@@ -27,6 +29,7 @@ Requires-Python: >=3.12
|
|
|
27
29
|
Project-URL: Homepage, https://github.com/strawberry-graphql/strawberry-orm
|
|
28
30
|
Project-URL: Repository, https://github.com/strawberry-graphql/strawberry-orm
|
|
29
31
|
Project-URL: Issues, https://github.com/strawberry-graphql/strawberry-orm/issues
|
|
32
|
+
Provides-Extra: contrib-mcp
|
|
30
33
|
Provides-Extra: dev
|
|
31
34
|
Provides-Extra: django
|
|
32
35
|
Provides-Extra: sqlalchemy
|
|
@@ -48,7 +51,7 @@ Backend-agnostic schema generation for [Strawberry GraphQL](https://strawberry.r
|
|
|
48
51
|
|
|
49
52
|
**Before you ship:** [Security](#security) · [Production baseline](#production-baseline)
|
|
50
53
|
|
|
51
|
-
**Feature guide:** [Defining types](#defining-types) · [Declaring fields](#declaring-fields) · [Filters and ordering](#filters-and-ordering) · [Custom filters and ordering](#custom-filters-and-ordering) · [Grouping and aggregation](#grouping-and-aggregation) · [Payloads](#data--errors-payloads) · [Mutations](#mutations) · [Relay](#relay-integration) · [Async](#async-usage)
|
|
54
|
+
**Feature guide:** [Defining types](#defining-types) · [Declaring fields](#declaring-fields) · [Filters and ordering](#filters-and-ordering) · [Custom filters and ordering](#custom-filters-and-ordering) · [Grouping and aggregation](#grouping-and-aggregation) · [Payloads](#data--errors-payloads) · [Mutations](#mutations) · [Relay](#relay-integration) · [Async](#async-usage) · [Contrib](#contrib)
|
|
52
55
|
|
|
53
56
|
**Reference:** [API reference](API_REFERENCE.md) · [Backend options](#backend-options) · [Public exports](#public-exports) · [Full example](#appendix-full-example)
|
|
54
57
|
|
|
@@ -192,7 +195,7 @@ byline(self, ...) is not a scope: a scope receives (query, info) and never
|
|
|
192
195
|
sees the parent row. Use orm.field.lazy for a resolver that needs self.
|
|
193
196
|
```
|
|
194
197
|
|
|
195
|
-
[Declaring fields](#declaring-fields) covers how to choose
|
|
198
|
+
[Declaring fields](#declaring-fields) covers how to choose and what else the library checks.
|
|
196
199
|
|
|
197
200
|
### Connections
|
|
198
201
|
|
|
@@ -355,9 +358,6 @@ Define it on the `@orm.type` class for the model **being loaded**. A nested quer
|
|
|
355
358
|
| `users { posts { … } }` | `UserType.scope_rows` | `PostType.scope_rows` |
|
|
356
359
|
| `posts { author { … } }` | `PostType.scope_rows` | `UserType.scope_rows` |
|
|
357
360
|
|
|
358
|
-
|
|
359
|
-
> Renamed from `get_queryset` in 0.15. The old name named a Django type that only two of the three backends use, and `get_` suggested it returns a fresh query rather than narrowing the one it is handed. `warn_missing_queryset` is now `warn_missing_scope`.
|
|
360
|
-
|
|
361
361
|
### Parent scoping does not flow to children
|
|
362
362
|
|
|
363
363
|
This is the mistake that bites hardest, so it is worth one careful example.
|
|
@@ -692,6 +692,7 @@ For `{ users { name posts { title } } }` the order is always `PostType.scope_row
|
|
|
692
692
|
- Filter depth, branch count, and `inList` size are capped
|
|
693
693
|
- `orm.ref()` provides explicit `unlink` and `delete` operations — both opt-in via `unlink=True` and `delete=True`
|
|
694
694
|
- When you use `orm.schema()` (optimizer enabled by default), nested relation loads honor each type's `scope_rows` — but **only for types where you define it** (the ORM warns at type registration when `scope_rows` is missing)
|
|
695
|
+
- Filters, ordering, group-by and aggregates cover only the columns and relations the GraphQL types they serve show — through `object:`, the type the relation returns. A column those types leave out, or show through a resolver of your own, `on=`, `compute=` or permission classes, cannot be filtered on, sorted by, grouped by, or read through `min`/`max` — any of which would reveal it. `orm.schema()` works this out for the types each schema reaches, and a kept field carries the tags of the type field it mirrors, so a tagged schema drops both together
|
|
695
696
|
- Filtering through a relation (`filter: { object: { author: … } }`) is restricted to the rows the related type's `scope_rows` allows, so a filter cannot confirm values on rows the caller cannot read
|
|
696
697
|
- Ordering through a relation into a scoped type is **rejected when `orm.schema()` builds**, because the resulting sequence would itself rank hidden rows — see [Ordering into a scoped type](#ordering-into-a-scoped-type)
|
|
697
698
|
- Connection `aggregates` and `groups` are computed with the type's `scope_rows` applied, so counts and sums cover only readable rows
|
|
@@ -703,7 +704,7 @@ For `{ users { name posts { title } } }` the order is always `PostType.scope_row
|
|
|
703
704
|
| ---------------- | ----------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
|
|
704
705
|
| Authentication | — | middleware, `info.context`, permission classes |
|
|
705
706
|
| Row access | `scope_rows` per exposed type | define on **every** model type clients can reach — [parent scoping does not flow to children](#parent-scoping-does-not-flow-to-children) |
|
|
706
|
-
| Column exposure |
|
|
707
|
+
| Column exposure | inputs follow the type's fields | `exclude=[...]` on `@orm.type`, or `orm.field.eager(permission_classes=…)` |
|
|
707
708
|
| Query size | — | `default_query_limit` |
|
|
708
709
|
| Mutations | — | auth in resolvers; `authorize` callback on `apply_ref_list` |
|
|
709
710
|
| Custom resolvers | — | same as hand-written DB access — you own scoping |
|
|
@@ -763,7 +764,7 @@ Each one links to the mechanics.
|
|
|
763
764
|
| ------------------------------------------------------------------------------------------------ | ------------------------------------------------------ | ------------------------------------------------------------------------------------- |
|
|
764
765
|
| Parent `scope_rows` used to scope children, including via a join like `posts__is_published=True` | Tests existence of a child, does not filter children | [Parent scoping does not flow to children](#parent-scoping-does-not-flow-to-children) |
|
|
765
766
|
| A relation resolver that materializes — `list(self.posts.all())`, `.first()` | Skips `scope_rows` and the optimizer entirely | [Resolver kinds](#resolver-kinds) |
|
|
766
|
-
| `strawberry.Schema` instead of `orm.schema()` | Nested scoping hooks never run on Django or SQLAlchemy | `[orm.schema()](#ormschema)` |
|
|
767
|
+
| `strawberry.Schema` instead of `orm.schema()` | Nested scoping hooks never run on Django or SQLAlchemy, and inputs cover every column | `[orm.schema()](#ormschema)` |
|
|
767
768
|
| A root resolver returning instances | Optimizer cannot prefetch or scope anything below | [Root custom query](#root-custom-query) |
|
|
768
769
|
| `scope_rows` that ignores `info.context` | Hardcoded tenant or user filters leak across requests | `[scope_rows](#scope_rows--one-model-one-type)` |
|
|
769
770
|
| `@orm.type` exposing secrets through `auto` | Output types do not hide sensitive columns for you | [Defining Types](#defining-types) |
|
|
@@ -1053,46 +1054,6 @@ Names are validated when the type is defined, so a typo fails immediately:
|
|
|
1053
1054
|
ValueError: PostType.byline: Post has no relation 'athor'. Did you mean 'author'?
|
|
1054
1055
|
```
|
|
1055
1056
|
|
|
1056
|
-
Migrating from 0.14
|
|
1057
|
-
|
|
1058
|
-
These spellings were removed in 0.15; there are no deprecation shims.
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
| 0.14 | 0.15 |
|
|
1062
|
-
| ------------------------------------- | -------------------------------------- |
|
|
1063
|
-
| `@orm.field` (bare) | `@orm.field.custom` |
|
|
1064
|
-
| `orm.field()`, `orm.field(filters=…)` | `orm.field.auto(...)` |
|
|
1065
|
-
| `orm.field(hint=…, scope=…)` | `orm.field.auto(using=…, scope=…)` |
|
|
1066
|
-
| `make_field(permission_classes=…)` | `orm.field.auto(permission_classes=…)` |
|
|
1067
|
-
| `@orm.computed_field(hint=…)` | `@orm.field.computed(using=…)` |
|
|
1068
|
-
| `hint=[...]` | `using=[...]` |
|
|
1069
|
-
| `load=[...]` / `load=callable` | `using=[...]` / `scope=callable` |
|
|
1070
|
-
| `only=[...]` | removed — every column loads |
|
|
1071
|
-
| `get_queryset(cls, qs, info)` | `scope_rows(cls, query, info)` |
|
|
1072
|
-
| `warn_missing_queryset=` | `warn_missing_scope=` |
|
|
1073
|
-
| `scope=lambda qs: …` | `scope=lambda qs, info: …` |
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
Migrating to 0.19
|
|
1079
|
-
|
|
1080
|
-
`orm.field` and `orm.connection` each collapsed to two names. The old ones still work.
|
|
1081
|
-
|
|
1082
|
-
| Before | Now |
|
|
1083
|
-
| --- | --- |
|
|
1084
|
-
| `orm.field.auto(...)` | `orm.field.eager(...)` |
|
|
1085
|
-
| `orm.field.scoped(fn)` | `orm.field.eager(fn)` |
|
|
1086
|
-
| `orm.field.custom(fn)` | `orm.field.lazy(fn)` |
|
|
1087
|
-
| `orm.field.computed(fn, using=…)` | `orm.field.lazy(fn, using=…)` |
|
|
1088
|
-
| `orm.field.auto(using=…)` | drop it — see below |
|
|
1089
|
-
| `orm.connection(...)` | `orm.connection.eager()` / `.lazy(resolver=…)` |
|
|
1090
|
-
|
|
1091
|
-
Two behaviour changes worth knowing about:
|
|
1092
|
-
|
|
1093
|
-
- `using=` is gone from `eager`. It exists to disclose relations the optimizer cannot see being read, and only a resolver hides anything, so it now lives on `lazy` alone. `auto(using=…)` still works and still registers the hint, as it always did.
|
|
1094
|
-
- `orm.connection` used to accept and ignore any keyword it did not recognise, so a misspelled or unsupported one silently did nothing. Unknown keywords now raise, and `scope=` genuinely narrows the connection — including `totalCount` and `aggregates`, not just `edges`.
|
|
1095
|
-
|
|
1096
1057
|
### List fields
|
|
1097
1058
|
|
|
1098
1059
|
`orm.field.eager()` builds a list resolver from the model attached to the return type:
|
|
@@ -1136,6 +1097,8 @@ List fields returning `UserType` then accept a `filter` argument:
|
|
|
1136
1097
|
}
|
|
1137
1098
|
```
|
|
1138
1099
|
|
|
1100
|
+
The filter covers what `UserType` shows — `id`, `name` and `email` here — and `object:` reaches only the relations it shows. A column the type leaves out is not filterable, because a filter on it would read it one `startsWith` probe at a time; to filter on a column, show it on the type. The same holds for `orm.order()`, `orm.group()` and aggregates. Through `object:`, a filter covers the type the relation returns: under `posts(filter: {object: {author: …}})`, whatever `PostType.author`'s type shows. `orm.schema()` works this out for the types each schema reaches, so an admin schema can filter on a column a public schema hides even when both use the same filter; within one schema, an input serving several types covers what all of them show. A schema built with `strawberry.Schema` directly gets the inputs uncut.
|
|
1101
|
+
|
|
1139
1102
|
#### Filter shape
|
|
1140
1103
|
|
|
1141
1104
|
Filters are recursive `@oneOf` trees supporting `field`, `all`, `any`, `not`, and `oneOf`:
|
|
@@ -2044,6 +2007,8 @@ This gives you:
|
|
|
2044
2007
|
|
|
2045
2008
|
Filters and ordering are applied *before* pagination, so the connection always slices from a correctly filtered and sorted result set.
|
|
2046
2009
|
|
|
2010
|
+
`orm.connection` raises a `TypeError` for a keyword it does not accept, listing the ones it does, so a misspelling fails where you write it.
|
|
2011
|
+
|
|
2047
2012
|
The page is cut in the database, not in Python. `first: 50` reads 51 rows (the extra one answers `hasNextPage`), `after` becomes an `OFFSET`, and `totalCount` is a separate count sent only when it is selected — and not even then when the page comes back short, because a short page is the end of the result. `last` without `before` counts first, to find where the window starts. Cursors are the same either way. Each page is its own query, and a database may break ties in a non-unique order differently from one query to the next, so a row could land on two pages and another on none. The cut therefore ends every order — the client's, the resolver's or the model's — with the primary key, unless it already includes it; with no order at all, the primary key alone orders the pages. Rows that do not tie keep their order. A Django queryset the resolver already sliced, or ordered with `.extra(order_by=...)`, is cut in the order it has.
|
|
2048
2013
|
|
|
2049
2014
|
A few requests are still read whole and sliced in Python: a resolver that returns rows rather than a query, `last: 0` (which Relay defines as every row after the cursor), and, on SQLAlchemy, a join that can repeat a row — to a collection, or through a second `FROM` — without `.distinct()`. SQLAlchemy folds those repeats together with `.unique()` after reading, so a `LIMIT` would count them against the page.
|
|
@@ -2107,19 +2072,102 @@ class Query:
|
|
|
2107
2072
|
|
|
2108
2073
|
`apply_ref_list` is sync for Django/sync-SQLAlchemy and awaitable for Tortoise/async-SQLAlchemy.
|
|
2109
2074
|
|
|
2110
|
-
|
|
2075
|
+
---
|
|
2076
|
+
|
|
2077
|
+
## Contrib
|
|
2078
|
+
|
|
2079
|
+
Optional plugins live in `strawberry_orm.contrib`. Each has its own extra, so its dependencies are only installed when you ask for them.
|
|
2080
|
+
|
|
2081
|
+
### MCP: plain-language questions over your API
|
|
2082
|
+
|
|
2083
|
+
`strawberry_orm.contrib.mcp` serves a schema as an [MCP](https://modelcontextprotocol.io) server with a single tool, `ask(question)`. A model on your side reads the schema, writes one GraphQL query, and runs it through the schema as the caller. The caller gets back the query and its result. Its tool list holds one short tool instead of your whole schema.
|
|
2084
|
+
|
|
2085
|
+
```bash
|
|
2086
|
+
pip install "strawberry-orm[contrib.mcp]"
|
|
2087
|
+
```
|
|
2088
|
+
|
|
2089
|
+
```python
|
|
2090
|
+
from strawberry_orm.contrib.mcp import QueryAgent, mcp_server
|
|
2091
|
+
|
|
2092
|
+
agent = QueryAgent(
|
|
2093
|
+
schema, # e.g. orm.schema(query=Query, tags="mcp") to expose only part of it
|
|
2094
|
+
model="anthropic:claude-sonnet-5-5", # any provider:model that any-llm supports
|
|
2095
|
+
api_key=settings.ANTHROPIC_API_KEY, # or the provider's environment variable
|
|
2096
|
+
)
|
|
2097
|
+
|
|
2098
|
+
|
|
2099
|
+
async def get_context(request):
|
|
2100
|
+
user = await user_for_token(request.headers.get("authorization"))
|
|
2101
|
+
return {"request": request, "user": user}
|
|
2102
|
+
|
|
2103
|
+
|
|
2104
|
+
app = mcp_server(agent, context_getter=get_context).streamable_http_app()
|
|
2105
|
+
# uvicorn app:app, then point an MCP client at http://host:port/mcp
|
|
2106
|
+
```
|
|
2107
|
+
|
|
2108
|
+
```json
|
|
2109
|
+
{"query": "{ users(filter: {field: {email: {iContains: \"example.com\"}}}) { id name } }",
|
|
2110
|
+
"variables": {},
|
|
2111
|
+
"data": {"users": [{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}]}}
|
|
2112
|
+
```
|
|
2113
|
+
|
|
2114
|
+
- **Models are swappable.** Models are called through [any-llm](https://github.com/mozilla-ai/any-llm), so changing `model=` from `"anthropic:…"` to `"openai:…"` is the whole change. Other providers need any-llm's extra for them, for example `pip install "any-llm-sdk[mistral]"` for `"mistral:…"`. Extra keyword arguments (`temperature=`, `api_base=`, …) go to the model call.
|
|
2115
|
+
- **Your permissions apply.** The query runs through `schema.execute` with the context from `context_getter`, so `scope_rows`, `scope=`, permission classes and the optimizer behave as for any other request. Over stdio, `context_getter` receives `None`.
|
|
2116
|
+
- **Authenticate it.** `mcp_server` adds no authentication of its own, and every call runs the model on your key. Pass `token_verifier=` and `auth=`, or serve it behind your own, before anyone else can reach it; `before_query` can enforce a quota.
|
|
2117
|
+
- **Reads only, unless you opt in.** The model only sees the query side of the schema, and anything but a query is rejected when it runs. Pass `allow_mutations=True` to show and allow mutations.
|
|
2118
|
+
- **Changes are confirmed.** With mutations allowed, each one is shown to the person asking and runs only once they confirm it (`confirm_mutations=False` turns this off). The MCP client shows the form, so a confirmation is only as good as the client: one that fills in forms itself confirms on its user's behalf. A paused confirmation runs once, within `confirm_within` seconds (default 600). The agent remembers which ran in its own process, so across several processes a resent state can run its change again until it expires; keep such mutations idempotent.
|
|
2119
|
+
- **Checked before it runs.** An operation must be a single operation within `max_depth` levels (default 10) that passes validation. When it fails, the model sees the errors and tries again, up to `max_attempts` (default 3). Depth does not bound width, so give the schema Strawberry's `MaxAliasesLimiter` or `MaxTokensLimiter` to cap that; they apply here as to any request.
|
|
2120
|
+
- **Rows stay out of the model.** The model sees the question, the schema, and the errors from its own attempts. The data goes straight back to the caller, unless you turn on lookups (below). Errors are passed on as they are, so one that quotes a stored value shows the model that value.
|
|
2121
|
+
- **Failures are tool errors.** If the model says the schema can't answer the question, or every attempt fails, the tool returns an error with the reason and the last query tried.
|
|
2122
|
+
|
|
2123
|
+
#### Clarifying questions
|
|
2124
|
+
|
|
2125
|
+
When a question leaves out something the query needs ("posts by *which* author?"), the model can ask instead of guessing. It sends one short question with typed fields, and the server shows it as an [elicitation](https://modelcontextprotocol.io/specification/2025-11-25/client/elicitation) form in whatever way the client supports:
|
|
2126
|
+
|
|
2127
|
+
| Client | What happens |
|
|
2128
|
+
| --- | --- |
|
|
2129
|
+
| 2026-07-28 or later, with forms | `ask` returns `input_required`; the client shows the form and calls again with the answers. The agent's progress travels in the request state, which the MCP SDK encrypts. |
|
|
2130
|
+
| Older, with forms | The form is shown during the call. |
|
|
2131
|
+
| No forms | `ask` returns `{"needs_input": {"kind", "message", "schema"}}`, so the calling AI can ask its user and call again with a fuller question. A mutation that needs confirming is refused. |
|
|
2132
|
+
|
|
2133
|
+
`clarify=False` turns questions off; `max_clarifications` (default 1) caps them per call. Request state is sealed with a key held by the server process, so a deployment with several processes passes a shared one: `mcp_server(agent, request_state_security=RequestStateSecurity(keys=[secret]))`.
|
|
2134
|
+
|
|
2135
|
+
#### Lookups
|
|
2136
|
+
|
|
2137
|
+
With `lookups=True` the model may run up to `max_lookups` (default 3) small read-only queries and see their rows, at most `max_lookup_rows` (default 20) of each list. That lets it find the exact value to filter on, or offer real choices ("Alice Smith or Alice Jones?"). Lookups run with the caller's permissions like everything else, so the model only sees rows the caller could see. They are off by default because, with them on, rows reach the model — including rows other users wrote, which may carry instructions aimed at it. With mutations allowed, keep `confirm_mutations` on so nothing a row says can change data unasked; the agent warns when it is off.
|
|
2138
|
+
|
|
2139
|
+
#### Hooks
|
|
2140
|
+
|
|
2141
|
+
Both receive the GraphQL context and may be sync or async.
|
|
2142
|
+
|
|
2143
|
+
```python
|
|
2144
|
+
from strawberry_orm.contrib.mcp import QueryAgentError, QueryRejected
|
|
2145
|
+
|
|
2146
|
+
|
|
2147
|
+
def answer_from_the_user(clarification, context):
|
|
2148
|
+
# Answer what the app already knows instead of asking.
|
|
2149
|
+
if clarification.kind == "question" and clarification.fields == ["team"]:
|
|
2150
|
+
return {"team": context["user"].team}
|
|
2151
|
+
return None # ask the person
|
|
2152
|
+
|
|
2153
|
+
|
|
2154
|
+
async def guard(query, variables, context):
|
|
2155
|
+
if await over_quota(context["user"]):
|
|
2156
|
+
raise QueryAgentError("Daily question limit reached.") # stop
|
|
2157
|
+
if "first:" not in query:
|
|
2158
|
+
raise QueryRejected("Page with first: 50 or fewer.") # the model tries again
|
|
2159
|
+
|
|
2160
|
+
|
|
2161
|
+
agent = QueryAgent(schema, model=..., on_clarify=answer_from_the_user, before_query=guard)
|
|
2162
|
+
```
|
|
2111
2163
|
|
|
2112
|
-
|
|
2164
|
+
#### Without MCP
|
|
2113
2165
|
|
|
2166
|
+
`QueryAgent.ask(question, context=..., clarifier=...)` works anywhere, for example behind a chat endpoint. `clarifier` is an async function that puts a `Clarification` to the person and returns their answers (or `None` if they decline). Without one, a clarification pauses the agent and `ask` returns `{"needs_input": ..., "state": ...}`; call `agent.resume(state, answers, context=...)` once you have them. `state` is plain JSON, so it can be stored between requests, but it holds the conversation so far, so keep it server-side or encrypt it.
|
|
2114
2167
|
|
|
2115
|
-
|
|
2116
|
-
| ---------------------------------------- | ---------------------------------------------------- |
|
|
2117
|
-
| `_patch_orm_filter_extension_for_async` | `_AutoFilterOrderExtension` async/sync paths |
|
|
2118
|
-
| `@orm.type` + `_ensure_async_resolver` | `django_async_safe` + `@orm.type` post-processing |
|
|
2119
|
-
| Custom resolver without filter extension | `@orm.field.lazy` (no `_AutoFilterOrderExtension`) |
|
|
2120
|
-
| `_materialize_django_result` | `materialize_query` / extension materialization |
|
|
2121
|
-
| Manual `is_type_of` | Automatic on `@orm.type(Model)` |
|
|
2168
|
+
`instructions=` adds your own guidance to the model's prompt, and `mcp_server(..., description=...)` replaces the tool description, which by default lists the root fields. Other keyword arguments go to `MCPServer`, for example `token_verifier=` and `auth=` for OAuth.
|
|
2122
2169
|
|
|
2170
|
+
To try it locally, `python cli.py mcp` serves the seeded SQLAlchemy test schema on `http://localhost:8421/mcp`, reading the key from `ANTHROPIC_API_KEY`. Add `--lookups` and `--allow-mutations` to try those.
|
|
2123
2171
|
|
|
2124
2172
|
---
|
|
2125
2173
|
|
|
@@ -13,7 +13,7 @@ Backend-agnostic schema generation for [Strawberry GraphQL](https://strawberry.r
|
|
|
13
13
|
|
|
14
14
|
**Before you ship:** [Security](#security) · [Production baseline](#production-baseline)
|
|
15
15
|
|
|
16
|
-
**Feature guide:** [Defining types](#defining-types) · [Declaring fields](#declaring-fields) · [Filters and ordering](#filters-and-ordering) · [Custom filters and ordering](#custom-filters-and-ordering) · [Grouping and aggregation](#grouping-and-aggregation) · [Payloads](#data--errors-payloads) · [Mutations](#mutations) · [Relay](#relay-integration) · [Async](#async-usage)
|
|
16
|
+
**Feature guide:** [Defining types](#defining-types) · [Declaring fields](#declaring-fields) · [Filters and ordering](#filters-and-ordering) · [Custom filters and ordering](#custom-filters-and-ordering) · [Grouping and aggregation](#grouping-and-aggregation) · [Payloads](#data--errors-payloads) · [Mutations](#mutations) · [Relay](#relay-integration) · [Async](#async-usage) · [Contrib](#contrib)
|
|
17
17
|
|
|
18
18
|
**Reference:** [API reference](API_REFERENCE.md) · [Backend options](#backend-options) · [Public exports](#public-exports) · [Full example](#appendix-full-example)
|
|
19
19
|
|
|
@@ -157,7 +157,7 @@ byline(self, ...) is not a scope: a scope receives (query, info) and never
|
|
|
157
157
|
sees the parent row. Use orm.field.lazy for a resolver that needs self.
|
|
158
158
|
```
|
|
159
159
|
|
|
160
|
-
[Declaring fields](#declaring-fields) covers how to choose
|
|
160
|
+
[Declaring fields](#declaring-fields) covers how to choose and what else the library checks.
|
|
161
161
|
|
|
162
162
|
### Connections
|
|
163
163
|
|
|
@@ -320,9 +320,6 @@ Define it on the `@orm.type` class for the model **being loaded**. A nested quer
|
|
|
320
320
|
| `users { posts { … } }` | `UserType.scope_rows` | `PostType.scope_rows` |
|
|
321
321
|
| `posts { author { … } }` | `PostType.scope_rows` | `UserType.scope_rows` |
|
|
322
322
|
|
|
323
|
-
|
|
324
|
-
> Renamed from `get_queryset` in 0.15. The old name named a Django type that only two of the three backends use, and `get_` suggested it returns a fresh query rather than narrowing the one it is handed. `warn_missing_queryset` is now `warn_missing_scope`.
|
|
325
|
-
|
|
326
323
|
### Parent scoping does not flow to children
|
|
327
324
|
|
|
328
325
|
This is the mistake that bites hardest, so it is worth one careful example.
|
|
@@ -657,6 +654,7 @@ For `{ users { name posts { title } } }` the order is always `PostType.scope_row
|
|
|
657
654
|
- Filter depth, branch count, and `inList` size are capped
|
|
658
655
|
- `orm.ref()` provides explicit `unlink` and `delete` operations — both opt-in via `unlink=True` and `delete=True`
|
|
659
656
|
- When you use `orm.schema()` (optimizer enabled by default), nested relation loads honor each type's `scope_rows` — but **only for types where you define it** (the ORM warns at type registration when `scope_rows` is missing)
|
|
657
|
+
- Filters, ordering, group-by and aggregates cover only the columns and relations the GraphQL types they serve show — through `object:`, the type the relation returns. A column those types leave out, or show through a resolver of your own, `on=`, `compute=` or permission classes, cannot be filtered on, sorted by, grouped by, or read through `min`/`max` — any of which would reveal it. `orm.schema()` works this out for the types each schema reaches, and a kept field carries the tags of the type field it mirrors, so a tagged schema drops both together
|
|
660
658
|
- Filtering through a relation (`filter: { object: { author: … } }`) is restricted to the rows the related type's `scope_rows` allows, so a filter cannot confirm values on rows the caller cannot read
|
|
661
659
|
- Ordering through a relation into a scoped type is **rejected when `orm.schema()` builds**, because the resulting sequence would itself rank hidden rows — see [Ordering into a scoped type](#ordering-into-a-scoped-type)
|
|
662
660
|
- Connection `aggregates` and `groups` are computed with the type's `scope_rows` applied, so counts and sums cover only readable rows
|
|
@@ -668,7 +666,7 @@ For `{ users { name posts { title } } }` the order is always `PostType.scope_row
|
|
|
668
666
|
| ---------------- | ----------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
|
|
669
667
|
| Authentication | — | middleware, `info.context`, permission classes |
|
|
670
668
|
| Row access | `scope_rows` per exposed type | define on **every** model type clients can reach — [parent scoping does not flow to children](#parent-scoping-does-not-flow-to-children) |
|
|
671
|
-
| Column exposure |
|
|
669
|
+
| Column exposure | inputs follow the type's fields | `exclude=[...]` on `@orm.type`, or `orm.field.eager(permission_classes=…)` |
|
|
672
670
|
| Query size | — | `default_query_limit` |
|
|
673
671
|
| Mutations | — | auth in resolvers; `authorize` callback on `apply_ref_list` |
|
|
674
672
|
| Custom resolvers | — | same as hand-written DB access — you own scoping |
|
|
@@ -728,7 +726,7 @@ Each one links to the mechanics.
|
|
|
728
726
|
| ------------------------------------------------------------------------------------------------ | ------------------------------------------------------ | ------------------------------------------------------------------------------------- |
|
|
729
727
|
| Parent `scope_rows` used to scope children, including via a join like `posts__is_published=True` | Tests existence of a child, does not filter children | [Parent scoping does not flow to children](#parent-scoping-does-not-flow-to-children) |
|
|
730
728
|
| A relation resolver that materializes — `list(self.posts.all())`, `.first()` | Skips `scope_rows` and the optimizer entirely | [Resolver kinds](#resolver-kinds) |
|
|
731
|
-
| `strawberry.Schema` instead of `orm.schema()` | Nested scoping hooks never run on Django or SQLAlchemy | `[orm.schema()](#ormschema)` |
|
|
729
|
+
| `strawberry.Schema` instead of `orm.schema()` | Nested scoping hooks never run on Django or SQLAlchemy, and inputs cover every column | `[orm.schema()](#ormschema)` |
|
|
732
730
|
| A root resolver returning instances | Optimizer cannot prefetch or scope anything below | [Root custom query](#root-custom-query) |
|
|
733
731
|
| `scope_rows` that ignores `info.context` | Hardcoded tenant or user filters leak across requests | `[scope_rows](#scope_rows--one-model-one-type)` |
|
|
734
732
|
| `@orm.type` exposing secrets through `auto` | Output types do not hide sensitive columns for you | [Defining Types](#defining-types) |
|
|
@@ -1018,46 +1016,6 @@ Names are validated when the type is defined, so a typo fails immediately:
|
|
|
1018
1016
|
ValueError: PostType.byline: Post has no relation 'athor'. Did you mean 'author'?
|
|
1019
1017
|
```
|
|
1020
1018
|
|
|
1021
|
-
Migrating from 0.14
|
|
1022
|
-
|
|
1023
|
-
These spellings were removed in 0.15; there are no deprecation shims.
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
| 0.14 | 0.15 |
|
|
1027
|
-
| ------------------------------------- | -------------------------------------- |
|
|
1028
|
-
| `@orm.field` (bare) | `@orm.field.custom` |
|
|
1029
|
-
| `orm.field()`, `orm.field(filters=…)` | `orm.field.auto(...)` |
|
|
1030
|
-
| `orm.field(hint=…, scope=…)` | `orm.field.auto(using=…, scope=…)` |
|
|
1031
|
-
| `make_field(permission_classes=…)` | `orm.field.auto(permission_classes=…)` |
|
|
1032
|
-
| `@orm.computed_field(hint=…)` | `@orm.field.computed(using=…)` |
|
|
1033
|
-
| `hint=[...]` | `using=[...]` |
|
|
1034
|
-
| `load=[...]` / `load=callable` | `using=[...]` / `scope=callable` |
|
|
1035
|
-
| `only=[...]` | removed — every column loads |
|
|
1036
|
-
| `get_queryset(cls, qs, info)` | `scope_rows(cls, query, info)` |
|
|
1037
|
-
| `warn_missing_queryset=` | `warn_missing_scope=` |
|
|
1038
|
-
| `scope=lambda qs: …` | `scope=lambda qs, info: …` |
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
Migrating to 0.19
|
|
1044
|
-
|
|
1045
|
-
`orm.field` and `orm.connection` each collapsed to two names. The old ones still work.
|
|
1046
|
-
|
|
1047
|
-
| Before | Now |
|
|
1048
|
-
| --- | --- |
|
|
1049
|
-
| `orm.field.auto(...)` | `orm.field.eager(...)` |
|
|
1050
|
-
| `orm.field.scoped(fn)` | `orm.field.eager(fn)` |
|
|
1051
|
-
| `orm.field.custom(fn)` | `orm.field.lazy(fn)` |
|
|
1052
|
-
| `orm.field.computed(fn, using=…)` | `orm.field.lazy(fn, using=…)` |
|
|
1053
|
-
| `orm.field.auto(using=…)` | drop it — see below |
|
|
1054
|
-
| `orm.connection(...)` | `orm.connection.eager()` / `.lazy(resolver=…)` |
|
|
1055
|
-
|
|
1056
|
-
Two behaviour changes worth knowing about:
|
|
1057
|
-
|
|
1058
|
-
- `using=` is gone from `eager`. It exists to disclose relations the optimizer cannot see being read, and only a resolver hides anything, so it now lives on `lazy` alone. `auto(using=…)` still works and still registers the hint, as it always did.
|
|
1059
|
-
- `orm.connection` used to accept and ignore any keyword it did not recognise, so a misspelled or unsupported one silently did nothing. Unknown keywords now raise, and `scope=` genuinely narrows the connection — including `totalCount` and `aggregates`, not just `edges`.
|
|
1060
|
-
|
|
1061
1019
|
### List fields
|
|
1062
1020
|
|
|
1063
1021
|
`orm.field.eager()` builds a list resolver from the model attached to the return type:
|
|
@@ -1101,6 +1059,8 @@ List fields returning `UserType` then accept a `filter` argument:
|
|
|
1101
1059
|
}
|
|
1102
1060
|
```
|
|
1103
1061
|
|
|
1062
|
+
The filter covers what `UserType` shows — `id`, `name` and `email` here — and `object:` reaches only the relations it shows. A column the type leaves out is not filterable, because a filter on it would read it one `startsWith` probe at a time; to filter on a column, show it on the type. The same holds for `orm.order()`, `orm.group()` and aggregates. Through `object:`, a filter covers the type the relation returns: under `posts(filter: {object: {author: …}})`, whatever `PostType.author`'s type shows. `orm.schema()` works this out for the types each schema reaches, so an admin schema can filter on a column a public schema hides even when both use the same filter; within one schema, an input serving several types covers what all of them show. A schema built with `strawberry.Schema` directly gets the inputs uncut.
|
|
1063
|
+
|
|
1104
1064
|
#### Filter shape
|
|
1105
1065
|
|
|
1106
1066
|
Filters are recursive `@oneOf` trees supporting `field`, `all`, `any`, `not`, and `oneOf`:
|
|
@@ -2009,6 +1969,8 @@ This gives you:
|
|
|
2009
1969
|
|
|
2010
1970
|
Filters and ordering are applied *before* pagination, so the connection always slices from a correctly filtered and sorted result set.
|
|
2011
1971
|
|
|
1972
|
+
`orm.connection` raises a `TypeError` for a keyword it does not accept, listing the ones it does, so a misspelling fails where you write it.
|
|
1973
|
+
|
|
2012
1974
|
The page is cut in the database, not in Python. `first: 50` reads 51 rows (the extra one answers `hasNextPage`), `after` becomes an `OFFSET`, and `totalCount` is a separate count sent only when it is selected — and not even then when the page comes back short, because a short page is the end of the result. `last` without `before` counts first, to find where the window starts. Cursors are the same either way. Each page is its own query, and a database may break ties in a non-unique order differently from one query to the next, so a row could land on two pages and another on none. The cut therefore ends every order — the client's, the resolver's or the model's — with the primary key, unless it already includes it; with no order at all, the primary key alone orders the pages. Rows that do not tie keep their order. A Django queryset the resolver already sliced, or ordered with `.extra(order_by=...)`, is cut in the order it has.
|
|
2013
1975
|
|
|
2014
1976
|
A few requests are still read whole and sliced in Python: a resolver that returns rows rather than a query, `last: 0` (which Relay defines as every row after the cursor), and, on SQLAlchemy, a join that can repeat a row — to a collection, or through a second `FROM` — without `.distinct()`. SQLAlchemy folds those repeats together with `.unique()` after reading, so a `LIMIT` would count them against the page.
|
|
@@ -2072,19 +2034,102 @@ class Query:
|
|
|
2072
2034
|
|
|
2073
2035
|
`apply_ref_list` is sync for Django/sync-SQLAlchemy and awaitable for Tortoise/async-SQLAlchemy.
|
|
2074
2036
|
|
|
2075
|
-
|
|
2037
|
+
---
|
|
2038
|
+
|
|
2039
|
+
## Contrib
|
|
2040
|
+
|
|
2041
|
+
Optional plugins live in `strawberry_orm.contrib`. Each has its own extra, so its dependencies are only installed when you ask for them.
|
|
2042
|
+
|
|
2043
|
+
### MCP: plain-language questions over your API
|
|
2044
|
+
|
|
2045
|
+
`strawberry_orm.contrib.mcp` serves a schema as an [MCP](https://modelcontextprotocol.io) server with a single tool, `ask(question)`. A model on your side reads the schema, writes one GraphQL query, and runs it through the schema as the caller. The caller gets back the query and its result. Its tool list holds one short tool instead of your whole schema.
|
|
2046
|
+
|
|
2047
|
+
```bash
|
|
2048
|
+
pip install "strawberry-orm[contrib.mcp]"
|
|
2049
|
+
```
|
|
2050
|
+
|
|
2051
|
+
```python
|
|
2052
|
+
from strawberry_orm.contrib.mcp import QueryAgent, mcp_server
|
|
2053
|
+
|
|
2054
|
+
agent = QueryAgent(
|
|
2055
|
+
schema, # e.g. orm.schema(query=Query, tags="mcp") to expose only part of it
|
|
2056
|
+
model="anthropic:claude-sonnet-5-5", # any provider:model that any-llm supports
|
|
2057
|
+
api_key=settings.ANTHROPIC_API_KEY, # or the provider's environment variable
|
|
2058
|
+
)
|
|
2059
|
+
|
|
2060
|
+
|
|
2061
|
+
async def get_context(request):
|
|
2062
|
+
user = await user_for_token(request.headers.get("authorization"))
|
|
2063
|
+
return {"request": request, "user": user}
|
|
2064
|
+
|
|
2065
|
+
|
|
2066
|
+
app = mcp_server(agent, context_getter=get_context).streamable_http_app()
|
|
2067
|
+
# uvicorn app:app, then point an MCP client at http://host:port/mcp
|
|
2068
|
+
```
|
|
2069
|
+
|
|
2070
|
+
```json
|
|
2071
|
+
{"query": "{ users(filter: {field: {email: {iContains: \"example.com\"}}}) { id name } }",
|
|
2072
|
+
"variables": {},
|
|
2073
|
+
"data": {"users": [{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}]}}
|
|
2074
|
+
```
|
|
2075
|
+
|
|
2076
|
+
- **Models are swappable.** Models are called through [any-llm](https://github.com/mozilla-ai/any-llm), so changing `model=` from `"anthropic:…"` to `"openai:…"` is the whole change. Other providers need any-llm's extra for them, for example `pip install "any-llm-sdk[mistral]"` for `"mistral:…"`. Extra keyword arguments (`temperature=`, `api_base=`, …) go to the model call.
|
|
2077
|
+
- **Your permissions apply.** The query runs through `schema.execute` with the context from `context_getter`, so `scope_rows`, `scope=`, permission classes and the optimizer behave as for any other request. Over stdio, `context_getter` receives `None`.
|
|
2078
|
+
- **Authenticate it.** `mcp_server` adds no authentication of its own, and every call runs the model on your key. Pass `token_verifier=` and `auth=`, or serve it behind your own, before anyone else can reach it; `before_query` can enforce a quota.
|
|
2079
|
+
- **Reads only, unless you opt in.** The model only sees the query side of the schema, and anything but a query is rejected when it runs. Pass `allow_mutations=True` to show and allow mutations.
|
|
2080
|
+
- **Changes are confirmed.** With mutations allowed, each one is shown to the person asking and runs only once they confirm it (`confirm_mutations=False` turns this off). The MCP client shows the form, so a confirmation is only as good as the client: one that fills in forms itself confirms on its user's behalf. A paused confirmation runs once, within `confirm_within` seconds (default 600). The agent remembers which ran in its own process, so across several processes a resent state can run its change again until it expires; keep such mutations idempotent.
|
|
2081
|
+
- **Checked before it runs.** An operation must be a single operation within `max_depth` levels (default 10) that passes validation. When it fails, the model sees the errors and tries again, up to `max_attempts` (default 3). Depth does not bound width, so give the schema Strawberry's `MaxAliasesLimiter` or `MaxTokensLimiter` to cap that; they apply here as to any request.
|
|
2082
|
+
- **Rows stay out of the model.** The model sees the question, the schema, and the errors from its own attempts. The data goes straight back to the caller, unless you turn on lookups (below). Errors are passed on as they are, so one that quotes a stored value shows the model that value.
|
|
2083
|
+
- **Failures are tool errors.** If the model says the schema can't answer the question, or every attempt fails, the tool returns an error with the reason and the last query tried.
|
|
2084
|
+
|
|
2085
|
+
#### Clarifying questions
|
|
2086
|
+
|
|
2087
|
+
When a question leaves out something the query needs ("posts by *which* author?"), the model can ask instead of guessing. It sends one short question with typed fields, and the server shows it as an [elicitation](https://modelcontextprotocol.io/specification/2025-11-25/client/elicitation) form in whatever way the client supports:
|
|
2088
|
+
|
|
2089
|
+
| Client | What happens |
|
|
2090
|
+
| --- | --- |
|
|
2091
|
+
| 2026-07-28 or later, with forms | `ask` returns `input_required`; the client shows the form and calls again with the answers. The agent's progress travels in the request state, which the MCP SDK encrypts. |
|
|
2092
|
+
| Older, with forms | The form is shown during the call. |
|
|
2093
|
+
| No forms | `ask` returns `{"needs_input": {"kind", "message", "schema"}}`, so the calling AI can ask its user and call again with a fuller question. A mutation that needs confirming is refused. |
|
|
2094
|
+
|
|
2095
|
+
`clarify=False` turns questions off; `max_clarifications` (default 1) caps them per call. Request state is sealed with a key held by the server process, so a deployment with several processes passes a shared one: `mcp_server(agent, request_state_security=RequestStateSecurity(keys=[secret]))`.
|
|
2096
|
+
|
|
2097
|
+
#### Lookups
|
|
2098
|
+
|
|
2099
|
+
With `lookups=True` the model may run up to `max_lookups` (default 3) small read-only queries and see their rows, at most `max_lookup_rows` (default 20) of each list. That lets it find the exact value to filter on, or offer real choices ("Alice Smith or Alice Jones?"). Lookups run with the caller's permissions like everything else, so the model only sees rows the caller could see. They are off by default because, with them on, rows reach the model — including rows other users wrote, which may carry instructions aimed at it. With mutations allowed, keep `confirm_mutations` on so nothing a row says can change data unasked; the agent warns when it is off.
|
|
2100
|
+
|
|
2101
|
+
#### Hooks
|
|
2102
|
+
|
|
2103
|
+
Both receive the GraphQL context and may be sync or async.
|
|
2104
|
+
|
|
2105
|
+
```python
|
|
2106
|
+
from strawberry_orm.contrib.mcp import QueryAgentError, QueryRejected
|
|
2107
|
+
|
|
2108
|
+
|
|
2109
|
+
def answer_from_the_user(clarification, context):
|
|
2110
|
+
# Answer what the app already knows instead of asking.
|
|
2111
|
+
if clarification.kind == "question" and clarification.fields == ["team"]:
|
|
2112
|
+
return {"team": context["user"].team}
|
|
2113
|
+
return None # ask the person
|
|
2114
|
+
|
|
2115
|
+
|
|
2116
|
+
async def guard(query, variables, context):
|
|
2117
|
+
if await over_quota(context["user"]):
|
|
2118
|
+
raise QueryAgentError("Daily question limit reached.") # stop
|
|
2119
|
+
if "first:" not in query:
|
|
2120
|
+
raise QueryRejected("Page with first: 50 or fewer.") # the model tries again
|
|
2121
|
+
|
|
2122
|
+
|
|
2123
|
+
agent = QueryAgent(schema, model=..., on_clarify=answer_from_the_user, before_query=guard)
|
|
2124
|
+
```
|
|
2076
2125
|
|
|
2077
|
-
|
|
2126
|
+
#### Without MCP
|
|
2078
2127
|
|
|
2128
|
+
`QueryAgent.ask(question, context=..., clarifier=...)` works anywhere, for example behind a chat endpoint. `clarifier` is an async function that puts a `Clarification` to the person and returns their answers (or `None` if they decline). Without one, a clarification pauses the agent and `ask` returns `{"needs_input": ..., "state": ...}`; call `agent.resume(state, answers, context=...)` once you have them. `state` is plain JSON, so it can be stored between requests, but it holds the conversation so far, so keep it server-side or encrypt it.
|
|
2079
2129
|
|
|
2080
|
-
|
|
2081
|
-
| ---------------------------------------- | ---------------------------------------------------- |
|
|
2082
|
-
| `_patch_orm_filter_extension_for_async` | `_AutoFilterOrderExtension` async/sync paths |
|
|
2083
|
-
| `@orm.type` + `_ensure_async_resolver` | `django_async_safe` + `@orm.type` post-processing |
|
|
2084
|
-
| Custom resolver without filter extension | `@orm.field.lazy` (no `_AutoFilterOrderExtension`) |
|
|
2085
|
-
| `_materialize_django_result` | `materialize_query` / extension materialization |
|
|
2086
|
-
| Manual `is_type_of` | Automatic on `@orm.type(Model)` |
|
|
2130
|
+
`instructions=` adds your own guidance to the model's prompt, and `mcp_server(..., description=...)` replaces the tool description, which by default lists the root fields. Other keyword arguments go to `MCPServer`, for example `token_verifier=` and `auth=` for OAuth.
|
|
2087
2131
|
|
|
2132
|
+
To try it locally, `python cli.py mcp` serves the seeded SQLAlchemy test schema on `http://localhost:8421/mcp`, reading the key from `ANTHROPIC_API_KEY`. Add `--lookups` and `--allow-mutations` to try those.
|
|
2088
2133
|
|
|
2089
2134
|
---
|
|
2090
2135
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "strawberry-orm"
|
|
3
|
-
version = "0.
|
|
3
|
+
version = "0.25.0"
|
|
4
4
|
description = "Unified, backend-agnostic ORM abstraction for Strawberry GraphQL"
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
license = "MIT"
|
|
@@ -34,6 +34,10 @@ Issues = "https://github.com/strawberry-graphql/strawberry-orm/issues"
|
|
|
34
34
|
django = ["django>=4.2"]
|
|
35
35
|
sqlalchemy = ["sqlalchemy>=2.0"]
|
|
36
36
|
tortoise = ["tortoise-orm>=0.25.0"]
|
|
37
|
+
"contrib.mcp" = [
|
|
38
|
+
"mcp>=2.3.0",
|
|
39
|
+
"any-llm-sdk>=1.40.1",
|
|
40
|
+
]
|
|
37
41
|
dev = [
|
|
38
42
|
"greenlet>=3.3.2",
|
|
39
43
|
"pytest>=8.0",
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "strawberry-orm"
|
|
3
|
-
version = "0.
|
|
3
|
+
version = "0.25.0"
|
|
4
4
|
description = "Unified, backend-agnostic ORM abstraction for Strawberry GraphQL"
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
license = "MIT"
|
|
@@ -32,6 +32,7 @@ Issues = "https://github.com/strawberry-graphql/strawberry-orm/issues"
|
|
|
32
32
|
django = ["django>=4.2"]
|
|
33
33
|
sqlalchemy = ["sqlalchemy>=2.0"]
|
|
34
34
|
tortoise = ["tortoise-orm>=0.25.0"]
|
|
35
|
+
"contrib.mcp" = ["mcp>=2.3.0", "any-llm-sdk>=1.40.1"]
|
|
35
36
|
dev = [
|
|
36
37
|
"greenlet>=3.3.2",
|
|
37
38
|
"pytest>=8.0",
|