datasette-mcp 0.1a0__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.
- datasette_mcp-0.1a0/LICENSE +201 -0
- datasette_mcp-0.1a0/PKG-INFO +96 -0
- datasette_mcp-0.1a0/README.md +78 -0
- datasette_mcp-0.1a0/datasette_mcp/__init__.py +283 -0
- datasette_mcp-0.1a0/datasette_mcp/hookspecs.py +8 -0
- datasette_mcp-0.1a0/datasette_mcp.egg-info/PKG-INFO +96 -0
- datasette_mcp-0.1a0/datasette_mcp.egg-info/SOURCES.txt +12 -0
- datasette_mcp-0.1a0/datasette_mcp.egg-info/dependency_links.txt +1 -0
- datasette_mcp-0.1a0/datasette_mcp.egg-info/entry_points.txt +2 -0
- datasette_mcp-0.1a0/datasette_mcp.egg-info/requires.txt +2 -0
- datasette_mcp-0.1a0/datasette_mcp.egg-info/top_level.txt +1 -0
- datasette_mcp-0.1a0/pyproject.toml +39 -0
- datasette_mcp-0.1a0/setup.cfg +4 -0
- datasette_mcp-0.1a0/tests/test_mcp.py +518 -0
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: datasette-mcp
|
|
3
|
+
Version: 0.1a0
|
|
4
|
+
Summary: Adds a /-/mcp MCP server to any Datasette instance
|
|
5
|
+
Author: Datasette
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/datasette/datasette-mcp
|
|
8
|
+
Project-URL: Changelog, https://github.com/datasette/datasette-mcp/releases
|
|
9
|
+
Project-URL: Issues, https://github.com/datasette/datasette-mcp/issues
|
|
10
|
+
Project-URL: CI, https://github.com/datasette/datasette-mcp/actions
|
|
11
|
+
Classifier: Framework :: Datasette
|
|
12
|
+
Requires-Python: >=3.10
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
License-File: LICENSE
|
|
15
|
+
Requires-Dist: datasette
|
|
16
|
+
Requires-Dist: mcp>=2.0.0
|
|
17
|
+
Dynamic: license-file
|
|
18
|
+
|
|
19
|
+
# datasette-mcp
|
|
20
|
+
|
|
21
|
+
[](https://pypi.org/project/datasette-mcp/)
|
|
22
|
+
[](https://github.com/datasette/datasette-mcp/releases)
|
|
23
|
+
[](https://github.com/datasette/datasette-mcp/actions/workflows/test.yml)
|
|
24
|
+
[](https://github.com/datasette/datasette-mcp/blob/main/LICENSE)
|
|
25
|
+
|
|
26
|
+
Adds a /-/mcp MCP server to any Datasette instance
|
|
27
|
+
|
|
28
|
+
## Installation
|
|
29
|
+
|
|
30
|
+
Install this plugin in the same environment as Datasette.
|
|
31
|
+
```bash
|
|
32
|
+
datasette install datasette-mcp
|
|
33
|
+
```
|
|
34
|
+
## Usage
|
|
35
|
+
|
|
36
|
+
Start Datasette as normal, then configure an MCP client to connect to:
|
|
37
|
+
|
|
38
|
+
```
|
|
39
|
+
http://localhost:8001/-/mcp
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
The endpoint uses MCP Streamable HTTP and exposes three read-only tools by
|
|
43
|
+
default:
|
|
44
|
+
|
|
45
|
+
- `list_databases` lists the databases available to the current Datasette
|
|
46
|
+
actor.
|
|
47
|
+
- `get_database_schema` returns the complete SQL schema for a database,
|
|
48
|
+
including tables, indexes, views, and triggers.
|
|
49
|
+
- `execute_sql` executes one read-only SQL statement and returns structured
|
|
50
|
+
columns, rows, and a truncation indicator.
|
|
51
|
+
|
|
52
|
+
Datasette database visibility and `execute-sql` permissions are enforced for
|
|
53
|
+
every tool call. SQL uses the same `validate_sql_select()` and read-only
|
|
54
|
+
`Database.execute()` path as Datasette's custom SQL interface.
|
|
55
|
+
|
|
56
|
+
## Registering additional MCP tools
|
|
57
|
+
|
|
58
|
+
Other Datasette plugins can add tools to this MCP server by implementing the
|
|
59
|
+
`register_mcp_tools(datasette, mcp)` plugin hook. The `mcp` argument is the
|
|
60
|
+
`MCPServer` for that Datasette instance, so implementations use the MCP Python
|
|
61
|
+
SDK's normal `@mcp.tool()` decorator:
|
|
62
|
+
|
|
63
|
+
```python
|
|
64
|
+
from datasette import hookimpl
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
@hookimpl
|
|
68
|
+
def register_mcp_tools(datasette, mcp):
|
|
69
|
+
@mcp.tool()
|
|
70
|
+
async def database_count() -> int:
|
|
71
|
+
"""Return the number of user-facing databases."""
|
|
72
|
+
return len(
|
|
73
|
+
[name for name in datasette.databases if name != "_internal"]
|
|
74
|
+
)
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
The hook itself is synchronous because tools are registered while the MCP
|
|
78
|
+
server is being constructed. Tool functions can be synchronous or asynchronous
|
|
79
|
+
and can use all of the input, output, context, and annotation features provided
|
|
80
|
+
by the MCP Python SDK.
|
|
81
|
+
|
|
82
|
+
Datasette-mcp registers `list_databases`, `get_database_schema`, and
|
|
83
|
+
`execute_sql` through this same hook.
|
|
84
|
+
|
|
85
|
+
## Development
|
|
86
|
+
|
|
87
|
+
To set up this plugin locally, first checkout the code. You can confirm it is available like this:
|
|
88
|
+
```bash
|
|
89
|
+
cd datasette-mcp
|
|
90
|
+
# Confirm the plugin is visible
|
|
91
|
+
uv run datasette plugins
|
|
92
|
+
```
|
|
93
|
+
To run the tests:
|
|
94
|
+
```bash
|
|
95
|
+
uv run pytest
|
|
96
|
+
```
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
# datasette-mcp
|
|
2
|
+
|
|
3
|
+
[](https://pypi.org/project/datasette-mcp/)
|
|
4
|
+
[](https://github.com/datasette/datasette-mcp/releases)
|
|
5
|
+
[](https://github.com/datasette/datasette-mcp/actions/workflows/test.yml)
|
|
6
|
+
[](https://github.com/datasette/datasette-mcp/blob/main/LICENSE)
|
|
7
|
+
|
|
8
|
+
Adds a /-/mcp MCP server to any Datasette instance
|
|
9
|
+
|
|
10
|
+
## Installation
|
|
11
|
+
|
|
12
|
+
Install this plugin in the same environment as Datasette.
|
|
13
|
+
```bash
|
|
14
|
+
datasette install datasette-mcp
|
|
15
|
+
```
|
|
16
|
+
## Usage
|
|
17
|
+
|
|
18
|
+
Start Datasette as normal, then configure an MCP client to connect to:
|
|
19
|
+
|
|
20
|
+
```
|
|
21
|
+
http://localhost:8001/-/mcp
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
The endpoint uses MCP Streamable HTTP and exposes three read-only tools by
|
|
25
|
+
default:
|
|
26
|
+
|
|
27
|
+
- `list_databases` lists the databases available to the current Datasette
|
|
28
|
+
actor.
|
|
29
|
+
- `get_database_schema` returns the complete SQL schema for a database,
|
|
30
|
+
including tables, indexes, views, and triggers.
|
|
31
|
+
- `execute_sql` executes one read-only SQL statement and returns structured
|
|
32
|
+
columns, rows, and a truncation indicator.
|
|
33
|
+
|
|
34
|
+
Datasette database visibility and `execute-sql` permissions are enforced for
|
|
35
|
+
every tool call. SQL uses the same `validate_sql_select()` and read-only
|
|
36
|
+
`Database.execute()` path as Datasette's custom SQL interface.
|
|
37
|
+
|
|
38
|
+
## Registering additional MCP tools
|
|
39
|
+
|
|
40
|
+
Other Datasette plugins can add tools to this MCP server by implementing the
|
|
41
|
+
`register_mcp_tools(datasette, mcp)` plugin hook. The `mcp` argument is the
|
|
42
|
+
`MCPServer` for that Datasette instance, so implementations use the MCP Python
|
|
43
|
+
SDK's normal `@mcp.tool()` decorator:
|
|
44
|
+
|
|
45
|
+
```python
|
|
46
|
+
from datasette import hookimpl
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@hookimpl
|
|
50
|
+
def register_mcp_tools(datasette, mcp):
|
|
51
|
+
@mcp.tool()
|
|
52
|
+
async def database_count() -> int:
|
|
53
|
+
"""Return the number of user-facing databases."""
|
|
54
|
+
return len(
|
|
55
|
+
[name for name in datasette.databases if name != "_internal"]
|
|
56
|
+
)
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
The hook itself is synchronous because tools are registered while the MCP
|
|
60
|
+
server is being constructed. Tool functions can be synchronous or asynchronous
|
|
61
|
+
and can use all of the input, output, context, and annotation features provided
|
|
62
|
+
by the MCP Python SDK.
|
|
63
|
+
|
|
64
|
+
Datasette-mcp registers `list_databases`, `get_database_schema`, and
|
|
65
|
+
`execute_sql` through this same hook.
|
|
66
|
+
|
|
67
|
+
## Development
|
|
68
|
+
|
|
69
|
+
To set up this plugin locally, first checkout the code. You can confirm it is available like this:
|
|
70
|
+
```bash
|
|
71
|
+
cd datasette-mcp
|
|
72
|
+
# Confirm the plugin is visible
|
|
73
|
+
uv run datasette plugins
|
|
74
|
+
```
|
|
75
|
+
To run the tests:
|
|
76
|
+
```bash
|
|
77
|
+
uv run pytest
|
|
78
|
+
```
|
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import base64
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from typing import TYPE_CHECKING, Any, Union
|
|
6
|
+
from weakref import WeakKeyDictionary
|
|
7
|
+
|
|
8
|
+
from datasette import hookimpl
|
|
9
|
+
from datasette.database import QueryInterrupted, Results
|
|
10
|
+
from datasette.plugins import pm
|
|
11
|
+
from datasette.utils import InvalidSql, sqlite3, validate_sql_select
|
|
12
|
+
from mcp.server.mcpserver import Context, MCPServer
|
|
13
|
+
from mcp.types import ToolAnnotations
|
|
14
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
15
|
+
from typing_extensions import TypedDict
|
|
16
|
+
|
|
17
|
+
from . import hookspecs
|
|
18
|
+
|
|
19
|
+
if TYPE_CHECKING:
|
|
20
|
+
from datasette.app import Datasette
|
|
21
|
+
from datasette.database import Database
|
|
22
|
+
|
|
23
|
+
pm.add_hookspecs(hookspecs)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class DatabaseList(TypedDict):
|
|
27
|
+
databases: list[str]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class DatabaseSchema(BaseModel):
|
|
31
|
+
database: str
|
|
32
|
+
sql_schema: str = Field(alias="schema")
|
|
33
|
+
|
|
34
|
+
model_config = ConfigDict(populate_by_name=True)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class BlobValue(TypedDict):
|
|
38
|
+
base64: str
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
CellValue = Union[str, int, float, bool, None, BlobValue]
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class QueryResults(TypedDict):
|
|
45
|
+
database: str
|
|
46
|
+
columns: list[str]
|
|
47
|
+
rows: list[list[CellValue]]
|
|
48
|
+
truncated: bool
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass
|
|
52
|
+
class _MCPState:
|
|
53
|
+
server: MCPServer
|
|
54
|
+
app: Any
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
READ_ONLY_ANNOTATIONS = ToolAnnotations(
|
|
58
|
+
read_only_hint=True,
|
|
59
|
+
open_world_hint=False,
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
_states: WeakKeyDictionary[Datasette, _MCPState] = WeakKeyDictionary()
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def create_mcp_server(datasette: Datasette) -> MCPServer:
|
|
66
|
+
"""Create the extensible MCP server for a Datasette instance."""
|
|
67
|
+
server = MCPServer(
|
|
68
|
+
"datasette",
|
|
69
|
+
instructions=(
|
|
70
|
+
"Call list_databases, then get_database_schema for the selected "
|
|
71
|
+
"database, then execute_sql to answer questions."
|
|
72
|
+
),
|
|
73
|
+
)
|
|
74
|
+
pm.hook.register_mcp_tools(datasette=datasette, mcp=server)
|
|
75
|
+
return server
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
@hookimpl
|
|
79
|
+
def register_mcp_tools(datasette: Datasette, mcp: MCPServer) -> None:
|
|
80
|
+
"""Register datasette-mcp's default tools."""
|
|
81
|
+
|
|
82
|
+
@mcp.tool(annotations=READ_ONLY_ANNOTATIONS)
|
|
83
|
+
async def list_databases(ctx: Context) -> DatabaseList:
|
|
84
|
+
"""List the databases available in this Datasette instance."""
|
|
85
|
+
actor = _actor_from_context(ctx)
|
|
86
|
+
databases = []
|
|
87
|
+
for name in sorted(datasette.databases):
|
|
88
|
+
if name == "_internal":
|
|
89
|
+
continue
|
|
90
|
+
if await _database_permission_allowed(
|
|
91
|
+
datasette,
|
|
92
|
+
actor,
|
|
93
|
+
"view-database",
|
|
94
|
+
name,
|
|
95
|
+
):
|
|
96
|
+
databases.append(name)
|
|
97
|
+
return {"databases": databases}
|
|
98
|
+
|
|
99
|
+
@mcp.tool(annotations=READ_ONLY_ANNOTATIONS)
|
|
100
|
+
async def get_database_schema(database: str, ctx: Context) -> DatabaseSchema:
|
|
101
|
+
"""Return the complete SQL schema for a database."""
|
|
102
|
+
db, _ = await _get_visible_database(datasette, ctx, database)
|
|
103
|
+
results = await db.execute(
|
|
104
|
+
"""
|
|
105
|
+
select type, name, sql
|
|
106
|
+
from sqlite_schema
|
|
107
|
+
where sql is not null
|
|
108
|
+
order by
|
|
109
|
+
case type
|
|
110
|
+
when 'table' then 0
|
|
111
|
+
when 'index' then 1
|
|
112
|
+
when 'view' then 2
|
|
113
|
+
when 'trigger' then 3
|
|
114
|
+
else 4
|
|
115
|
+
end,
|
|
116
|
+
name
|
|
117
|
+
"""
|
|
118
|
+
)
|
|
119
|
+
statements = []
|
|
120
|
+
for row in results.rows:
|
|
121
|
+
statement = row["sql"].rstrip()
|
|
122
|
+
if not statement.endswith(";"):
|
|
123
|
+
statement += ";"
|
|
124
|
+
statements.append(statement)
|
|
125
|
+
return DatabaseSchema(
|
|
126
|
+
database=database,
|
|
127
|
+
schema="\n".join(statements),
|
|
128
|
+
)
|
|
129
|
+
|
|
130
|
+
@mcp.tool(annotations=READ_ONLY_ANNOTATIONS)
|
|
131
|
+
async def execute_sql(database: str, sql: str, ctx: Context) -> QueryResults:
|
|
132
|
+
"""Execute one read-only SQL statement and return its tabular results."""
|
|
133
|
+
db, actor = await _get_visible_database(datasette, ctx, database)
|
|
134
|
+
if not await _database_permission_allowed(
|
|
135
|
+
datasette,
|
|
136
|
+
actor,
|
|
137
|
+
"execute-sql",
|
|
138
|
+
database,
|
|
139
|
+
):
|
|
140
|
+
raise PermissionError(
|
|
141
|
+
f"You do not have permission to execute SQL against database "
|
|
142
|
+
f"{database!r}."
|
|
143
|
+
)
|
|
144
|
+
results = await _execute_read_only_sql(db, sql)
|
|
145
|
+
rows = [[_serialize_cell(value) for value in row] for row in results.rows]
|
|
146
|
+
return {
|
|
147
|
+
"database": database,
|
|
148
|
+
"columns": results.columns,
|
|
149
|
+
"rows": rows,
|
|
150
|
+
"truncated": results.truncated,
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _get_state(datasette: Datasette) -> _MCPState:
|
|
155
|
+
state = _states.get(datasette)
|
|
156
|
+
if state is None:
|
|
157
|
+
server = create_mcp_server(datasette)
|
|
158
|
+
app = server.streamable_http_app(
|
|
159
|
+
streamable_http_path="/",
|
|
160
|
+
json_response=True,
|
|
161
|
+
host="0.0.0.0",
|
|
162
|
+
)
|
|
163
|
+
state = _MCPState(server=server, app=app)
|
|
164
|
+
_states[datasette] = state
|
|
165
|
+
return state
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
@hookimpl
|
|
169
|
+
def register_routes(datasette: Datasette) -> list[tuple[str, Any]]:
|
|
170
|
+
"""Register the Streamable HTTP endpoint at /-/mcp."""
|
|
171
|
+
state = _get_state(datasette)
|
|
172
|
+
|
|
173
|
+
async def mcp_route(scope: dict[str, Any], receive: Any, send: Any) -> None:
|
|
174
|
+
mcp_scope = dict(scope, path="/", raw_path=b"/")
|
|
175
|
+
await state.app(mcp_scope, receive, send)
|
|
176
|
+
|
|
177
|
+
return [(r"/-/mcp$", mcp_route)]
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
@hookimpl
|
|
181
|
+
def asgi_wrapper(datasette: Datasette) -> Any:
|
|
182
|
+
"""Run the MCP session manager for the Datasette ASGI lifespan."""
|
|
183
|
+
state = _get_state(datasette)
|
|
184
|
+
|
|
185
|
+
def wrap(app: Any) -> Any:
|
|
186
|
+
async def run(scope: dict[str, Any], receive: Any, send: Any) -> None:
|
|
187
|
+
if scope["type"] == "lifespan":
|
|
188
|
+
async with state.server.session_manager.run():
|
|
189
|
+
await app(scope, receive, send)
|
|
190
|
+
else:
|
|
191
|
+
await app(scope, receive, send)
|
|
192
|
+
|
|
193
|
+
return run
|
|
194
|
+
|
|
195
|
+
return wrap
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
@hookimpl
|
|
199
|
+
def skip_csrf(datasette: Datasette, scope: dict[str, Any]) -> bool:
|
|
200
|
+
"""Exempt MCP's unsafe HTTP methods from Datasette's form CSRF check."""
|
|
201
|
+
return scope.get("method") in {"POST", "DELETE"} and scope.get(
|
|
202
|
+
"path"
|
|
203
|
+
) == datasette.urls.path(
|
|
204
|
+
"/-/mcp",
|
|
205
|
+
)
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _actor_from_context(ctx: Context) -> dict[str, Any] | None:
|
|
209
|
+
request = ctx.request_context.request
|
|
210
|
+
scope = getattr(request, "scope", None)
|
|
211
|
+
if not isinstance(scope, dict):
|
|
212
|
+
return None
|
|
213
|
+
actor = scope.get("actor")
|
|
214
|
+
return actor if isinstance(actor, dict) else None
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
async def _database_permission_allowed(
|
|
218
|
+
datasette: Datasette,
|
|
219
|
+
actor: dict[str, Any] | None,
|
|
220
|
+
action: str,
|
|
221
|
+
database: str,
|
|
222
|
+
) -> bool:
|
|
223
|
+
"""Check a database permission using the Datasette API available."""
|
|
224
|
+
if hasattr(datasette, "allowed"):
|
|
225
|
+
from datasette.resources import DatabaseResource
|
|
226
|
+
|
|
227
|
+
await datasette.invoke_startup()
|
|
228
|
+
return await datasette.allowed(
|
|
229
|
+
action=action,
|
|
230
|
+
resource=DatabaseResource(database),
|
|
231
|
+
actor=actor,
|
|
232
|
+
)
|
|
233
|
+
return await datasette.permission_allowed(
|
|
234
|
+
actor,
|
|
235
|
+
action,
|
|
236
|
+
database,
|
|
237
|
+
default=True,
|
|
238
|
+
)
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
async def _get_visible_database(
|
|
242
|
+
datasette: Datasette,
|
|
243
|
+
ctx: Context,
|
|
244
|
+
database: str,
|
|
245
|
+
) -> tuple[Database, dict[str, Any] | None]:
|
|
246
|
+
actor = _actor_from_context(ctx)
|
|
247
|
+
if database == "_internal" or database not in datasette.databases:
|
|
248
|
+
raise ValueError(f"Database {database!r} does not exist or is not available.")
|
|
249
|
+
if not await _database_permission_allowed(
|
|
250
|
+
datasette,
|
|
251
|
+
actor,
|
|
252
|
+
"view-database",
|
|
253
|
+
database,
|
|
254
|
+
):
|
|
255
|
+
raise ValueError(f"Database {database!r} does not exist or is not available.")
|
|
256
|
+
return datasette.databases[database], actor
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
async def _execute_read_only_sql(
|
|
260
|
+
database: Database,
|
|
261
|
+
sql: str,
|
|
262
|
+
) -> Results:
|
|
263
|
+
try:
|
|
264
|
+
validate_sql_select(sql)
|
|
265
|
+
return await database.execute(
|
|
266
|
+
sql,
|
|
267
|
+
truncate=True,
|
|
268
|
+
log_sql_errors=False,
|
|
269
|
+
)
|
|
270
|
+
except InvalidSql as ex:
|
|
271
|
+
raise ValueError(str(ex)) from None
|
|
272
|
+
except QueryInterrupted:
|
|
273
|
+
raise ValueError("SQL query exceeded the configured time limit.") from None
|
|
274
|
+
except sqlite3.DatabaseError as ex:
|
|
275
|
+
raise ValueError(f"SQL error: {ex}") from None
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def _serialize_cell(value: object) -> CellValue:
|
|
279
|
+
if isinstance(value, bytes):
|
|
280
|
+
return {"base64": base64.b64encode(value).decode("ascii")}
|
|
281
|
+
if value is None or isinstance(value, (str, int, float, bool)):
|
|
282
|
+
return value
|
|
283
|
+
return str(value)
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: datasette-mcp
|
|
3
|
+
Version: 0.1a0
|
|
4
|
+
Summary: Adds a /-/mcp MCP server to any Datasette instance
|
|
5
|
+
Author: Datasette
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/datasette/datasette-mcp
|
|
8
|
+
Project-URL: Changelog, https://github.com/datasette/datasette-mcp/releases
|
|
9
|
+
Project-URL: Issues, https://github.com/datasette/datasette-mcp/issues
|
|
10
|
+
Project-URL: CI, https://github.com/datasette/datasette-mcp/actions
|
|
11
|
+
Classifier: Framework :: Datasette
|
|
12
|
+
Requires-Python: >=3.10
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
License-File: LICENSE
|
|
15
|
+
Requires-Dist: datasette
|
|
16
|
+
Requires-Dist: mcp>=2.0.0
|
|
17
|
+
Dynamic: license-file
|
|
18
|
+
|
|
19
|
+
# datasette-mcp
|
|
20
|
+
|
|
21
|
+
[](https://pypi.org/project/datasette-mcp/)
|
|
22
|
+
[](https://github.com/datasette/datasette-mcp/releases)
|
|
23
|
+
[](https://github.com/datasette/datasette-mcp/actions/workflows/test.yml)
|
|
24
|
+
[](https://github.com/datasette/datasette-mcp/blob/main/LICENSE)
|
|
25
|
+
|
|
26
|
+
Adds a /-/mcp MCP server to any Datasette instance
|
|
27
|
+
|
|
28
|
+
## Installation
|
|
29
|
+
|
|
30
|
+
Install this plugin in the same environment as Datasette.
|
|
31
|
+
```bash
|
|
32
|
+
datasette install datasette-mcp
|
|
33
|
+
```
|
|
34
|
+
## Usage
|
|
35
|
+
|
|
36
|
+
Start Datasette as normal, then configure an MCP client to connect to:
|
|
37
|
+
|
|
38
|
+
```
|
|
39
|
+
http://localhost:8001/-/mcp
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
The endpoint uses MCP Streamable HTTP and exposes three read-only tools by
|
|
43
|
+
default:
|
|
44
|
+
|
|
45
|
+
- `list_databases` lists the databases available to the current Datasette
|
|
46
|
+
actor.
|
|
47
|
+
- `get_database_schema` returns the complete SQL schema for a database,
|
|
48
|
+
including tables, indexes, views, and triggers.
|
|
49
|
+
- `execute_sql` executes one read-only SQL statement and returns structured
|
|
50
|
+
columns, rows, and a truncation indicator.
|
|
51
|
+
|
|
52
|
+
Datasette database visibility and `execute-sql` permissions are enforced for
|
|
53
|
+
every tool call. SQL uses the same `validate_sql_select()` and read-only
|
|
54
|
+
`Database.execute()` path as Datasette's custom SQL interface.
|
|
55
|
+
|
|
56
|
+
## Registering additional MCP tools
|
|
57
|
+
|
|
58
|
+
Other Datasette plugins can add tools to this MCP server by implementing the
|
|
59
|
+
`register_mcp_tools(datasette, mcp)` plugin hook. The `mcp` argument is the
|
|
60
|
+
`MCPServer` for that Datasette instance, so implementations use the MCP Python
|
|
61
|
+
SDK's normal `@mcp.tool()` decorator:
|
|
62
|
+
|
|
63
|
+
```python
|
|
64
|
+
from datasette import hookimpl
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
@hookimpl
|
|
68
|
+
def register_mcp_tools(datasette, mcp):
|
|
69
|
+
@mcp.tool()
|
|
70
|
+
async def database_count() -> int:
|
|
71
|
+
"""Return the number of user-facing databases."""
|
|
72
|
+
return len(
|
|
73
|
+
[name for name in datasette.databases if name != "_internal"]
|
|
74
|
+
)
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
The hook itself is synchronous because tools are registered while the MCP
|
|
78
|
+
server is being constructed. Tool functions can be synchronous or asynchronous
|
|
79
|
+
and can use all of the input, output, context, and annotation features provided
|
|
80
|
+
by the MCP Python SDK.
|
|
81
|
+
|
|
82
|
+
Datasette-mcp registers `list_databases`, `get_database_schema`, and
|
|
83
|
+
`execute_sql` through this same hook.
|
|
84
|
+
|
|
85
|
+
## Development
|
|
86
|
+
|
|
87
|
+
To set up this plugin locally, first checkout the code. You can confirm it is available like this:
|
|
88
|
+
```bash
|
|
89
|
+
cd datasette-mcp
|
|
90
|
+
# Confirm the plugin is visible
|
|
91
|
+
uv run datasette plugins
|
|
92
|
+
```
|
|
93
|
+
To run the tests:
|
|
94
|
+
```bash
|
|
95
|
+
uv run pytest
|
|
96
|
+
```
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
datasette_mcp/__init__.py
|
|
5
|
+
datasette_mcp/hookspecs.py
|
|
6
|
+
datasette_mcp.egg-info/PKG-INFO
|
|
7
|
+
datasette_mcp.egg-info/SOURCES.txt
|
|
8
|
+
datasette_mcp.egg-info/dependency_links.txt
|
|
9
|
+
datasette_mcp.egg-info/entry_points.txt
|
|
10
|
+
datasette_mcp.egg-info/requires.txt
|
|
11
|
+
datasette_mcp.egg-info/top_level.txt
|
|
12
|
+
tests/test_mcp.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
datasette_mcp
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "datasette-mcp"
|
|
3
|
+
version = "0.1a0"
|
|
4
|
+
description = "Adds a /-/mcp MCP server to any Datasette instance"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
authors = [{name = "Datasette"}]
|
|
7
|
+
license = "Apache-2.0"
|
|
8
|
+
classifiers=[
|
|
9
|
+
"Framework :: Datasette"
|
|
10
|
+
]
|
|
11
|
+
requires-python = ">=3.10"
|
|
12
|
+
dependencies = [
|
|
13
|
+
"datasette",
|
|
14
|
+
"mcp>=2.0.0"
|
|
15
|
+
]
|
|
16
|
+
|
|
17
|
+
[dependency-groups]
|
|
18
|
+
dev = [
|
|
19
|
+
"pytest",
|
|
20
|
+
"pytest-asyncio"
|
|
21
|
+
]
|
|
22
|
+
|
|
23
|
+
[build-system]
|
|
24
|
+
requires = ["setuptools"]
|
|
25
|
+
build-backend = "setuptools.build_meta"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
[project.urls]
|
|
29
|
+
Homepage = "https://github.com/datasette/datasette-mcp"
|
|
30
|
+
Changelog = "https://github.com/datasette/datasette-mcp/releases"
|
|
31
|
+
Issues = "https://github.com/datasette/datasette-mcp/issues"
|
|
32
|
+
CI = "https://github.com/datasette/datasette-mcp/actions"
|
|
33
|
+
|
|
34
|
+
[project.entry-points.datasette]
|
|
35
|
+
mcp = "datasette_mcp"
|
|
36
|
+
|
|
37
|
+
[tool.pytest.ini_options]
|
|
38
|
+
asyncio_mode = "strict"
|
|
39
|
+
asyncio_default_fixture_loop_scope = "function"
|
|
@@ -0,0 +1,518 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
from contextlib import asynccontextmanager
|
|
3
|
+
|
|
4
|
+
from mcp import Client
|
|
5
|
+
from mcp.client.streamable_http import streamable_http_client
|
|
6
|
+
from mcp.server.streamable_http_manager import StreamableHTTPSessionManager
|
|
7
|
+
from datasette import hookimpl
|
|
8
|
+
from datasette.app import Datasette
|
|
9
|
+
from datasette.plugins import pm
|
|
10
|
+
import httpx2
|
|
11
|
+
import pytest
|
|
12
|
+
import pytest_asyncio
|
|
13
|
+
|
|
14
|
+
from datasette_mcp import create_mcp_server, skip_csrf
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@pytest.mark.asyncio
|
|
18
|
+
async def test_plugin_is_installed():
|
|
19
|
+
datasette = Datasette(memory=True)
|
|
20
|
+
response = await datasette.client.get("/-/plugins.json")
|
|
21
|
+
assert response.status_code == 200
|
|
22
|
+
installed_plugins = {p["name"] for p in response.json()}
|
|
23
|
+
assert "datasette-mcp" in installed_plugins
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@pytest_asyncio.fixture
|
|
27
|
+
async def datasette(tmp_path):
|
|
28
|
+
datasette = Datasette([str(tmp_path / "test.db")])
|
|
29
|
+
database = datasette.get_database("test")
|
|
30
|
+
await database.execute_write_script(
|
|
31
|
+
"""
|
|
32
|
+
create table authors (
|
|
33
|
+
id integer primary key,
|
|
34
|
+
name text not null
|
|
35
|
+
);
|
|
36
|
+
create index authors_name_idx on authors(name);
|
|
37
|
+
create view author_names as
|
|
38
|
+
select name from authors;
|
|
39
|
+
create trigger authors_uppercase
|
|
40
|
+
after insert on authors
|
|
41
|
+
when new.name != upper(new.name)
|
|
42
|
+
begin
|
|
43
|
+
update authors set name = upper(new.name) where id = new.id;
|
|
44
|
+
end;
|
|
45
|
+
insert into authors (name) values ('Ada'), ('Grace');
|
|
46
|
+
"""
|
|
47
|
+
)
|
|
48
|
+
return datasette
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@pytest_asyncio.fixture
|
|
52
|
+
async def mcp_server(datasette):
|
|
53
|
+
return create_mcp_server(datasette)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@pytest.mark.asyncio
|
|
57
|
+
async def test_server_exposes_exactly_three_read_only_tools(mcp_server):
|
|
58
|
+
async with Client(mcp_server, raise_exceptions=True) as client:
|
|
59
|
+
tools = (await client.list_tools()).tools
|
|
60
|
+
|
|
61
|
+
assert [tool.name for tool in tools] == [
|
|
62
|
+
"list_databases",
|
|
63
|
+
"get_database_schema",
|
|
64
|
+
"execute_sql",
|
|
65
|
+
]
|
|
66
|
+
for tool in tools:
|
|
67
|
+
assert tool.input_schema
|
|
68
|
+
assert tool.output_schema
|
|
69
|
+
assert tool.description
|
|
70
|
+
assert tool.annotations.read_only_hint is True
|
|
71
|
+
assert tool.annotations.open_world_hint is False
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def test_default_tools_are_registered_by_plugin_hook():
|
|
75
|
+
implementations = pm.hook.register_mcp_tools.get_hookimpls()
|
|
76
|
+
|
|
77
|
+
assert any(
|
|
78
|
+
implementation.function.__module__ == "datasette_mcp"
|
|
79
|
+
for implementation in implementations
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
@pytest.mark.asyncio
|
|
84
|
+
async def test_another_plugin_can_register_an_mcp_tool(datasette):
|
|
85
|
+
seen_datasette = None
|
|
86
|
+
|
|
87
|
+
class ExtraToolsPlugin:
|
|
88
|
+
@hookimpl
|
|
89
|
+
def register_mcp_tools(self, datasette, mcp):
|
|
90
|
+
nonlocal seen_datasette
|
|
91
|
+
seen_datasette = datasette
|
|
92
|
+
|
|
93
|
+
@mcp.tool()
|
|
94
|
+
async def reverse_text(text: str) -> str:
|
|
95
|
+
"""Reverse the supplied text."""
|
|
96
|
+
return text[::-1]
|
|
97
|
+
|
|
98
|
+
plugin = ExtraToolsPlugin()
|
|
99
|
+
pm.register(plugin, name="ExtraToolsPlugin")
|
|
100
|
+
try:
|
|
101
|
+
async with Client(create_mcp_server(datasette)) as client:
|
|
102
|
+
tools = await client.list_tools()
|
|
103
|
+
result = await client.call_tool(
|
|
104
|
+
"reverse_text",
|
|
105
|
+
{"text": "Datasette"},
|
|
106
|
+
)
|
|
107
|
+
finally:
|
|
108
|
+
pm.unregister(name="ExtraToolsPlugin")
|
|
109
|
+
|
|
110
|
+
assert seen_datasette is datasette
|
|
111
|
+
assert "reverse_text" in {tool.name for tool in tools.tools}
|
|
112
|
+
assert result.structured_content == {"result": "ettesataD"}
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
@pytest.mark.asyncio
|
|
116
|
+
async def test_list_databases(mcp_server):
|
|
117
|
+
async with Client(mcp_server, raise_exceptions=True) as client:
|
|
118
|
+
result = await client.call_tool("list_databases")
|
|
119
|
+
|
|
120
|
+
assert result.is_error is False
|
|
121
|
+
assert result.structured_content == {"databases": ["test"]}
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
@pytest.mark.asyncio
|
|
125
|
+
async def test_get_database_schema_includes_all_schema_object_types(mcp_server):
|
|
126
|
+
async with Client(mcp_server, raise_exceptions=True) as client:
|
|
127
|
+
result = await client.call_tool("get_database_schema", {"database": "test"})
|
|
128
|
+
|
|
129
|
+
assert result.is_error is False
|
|
130
|
+
schema = result.structured_content["schema"]
|
|
131
|
+
assert "CREATE TABLE authors" in schema
|
|
132
|
+
assert "CREATE INDEX authors_name_idx" in schema
|
|
133
|
+
assert "CREATE VIEW author_names" in schema
|
|
134
|
+
assert "CREATE TRIGGER authors_uppercase" in schema
|
|
135
|
+
assert result.structured_content["database"] == "test"
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
@pytest.mark.asyncio
|
|
139
|
+
async def test_execute_sql_returns_structured_rows(mcp_server):
|
|
140
|
+
async with Client(mcp_server, raise_exceptions=True) as client:
|
|
141
|
+
result = await client.call_tool(
|
|
142
|
+
"execute_sql",
|
|
143
|
+
{
|
|
144
|
+
"database": "test",
|
|
145
|
+
"sql": """
|
|
146
|
+
select id, name, null as missing, x'0001' as payload
|
|
147
|
+
from authors
|
|
148
|
+
order by id
|
|
149
|
+
""",
|
|
150
|
+
},
|
|
151
|
+
)
|
|
152
|
+
|
|
153
|
+
assert result.is_error is False
|
|
154
|
+
assert result.structured_content == {
|
|
155
|
+
"database": "test",
|
|
156
|
+
"columns": ["id", "name", "missing", "payload"],
|
|
157
|
+
"rows": [
|
|
158
|
+
[1, "ADA", None, {"base64": "AAE="}],
|
|
159
|
+
[2, "GRACE", None, {"base64": "AAE="}],
|
|
160
|
+
],
|
|
161
|
+
"truncated": False,
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
@pytest.mark.asyncio
|
|
166
|
+
async def test_execute_sql_delegates_to_datasette_database_execute(
|
|
167
|
+
datasette,
|
|
168
|
+
monkeypatch,
|
|
169
|
+
):
|
|
170
|
+
database = datasette.get_database("test")
|
|
171
|
+
original_execute = database.execute
|
|
172
|
+
calls = []
|
|
173
|
+
|
|
174
|
+
async def execute(sql, **kwargs):
|
|
175
|
+
calls.append((sql, kwargs))
|
|
176
|
+
return await original_execute(sql, **kwargs)
|
|
177
|
+
|
|
178
|
+
monkeypatch.setattr(database, "execute", execute)
|
|
179
|
+
|
|
180
|
+
async with Client(create_mcp_server(datasette), raise_exceptions=True) as client:
|
|
181
|
+
result = await client.call_tool(
|
|
182
|
+
"execute_sql",
|
|
183
|
+
{"database": "test", "sql": "select 42 as answer"},
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
assert result.structured_content["rows"] == [[42]]
|
|
187
|
+
assert calls[-1] == (
|
|
188
|
+
"select 42 as answer",
|
|
189
|
+
{"truncate": True, "log_sql_errors": False},
|
|
190
|
+
)
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def tool_error_text(result):
|
|
194
|
+
assert result.is_error is True
|
|
195
|
+
return "\n".join(content.text for content in result.content)
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
@asynccontextmanager
|
|
199
|
+
async def run_asgi_lifespan(app):
|
|
200
|
+
to_app = asyncio.Queue()
|
|
201
|
+
from_app = asyncio.Queue()
|
|
202
|
+
scope = {
|
|
203
|
+
"type": "lifespan",
|
|
204
|
+
"asgi": {"version": "3.0", "spec_version": "2.0"},
|
|
205
|
+
"state": {},
|
|
206
|
+
}
|
|
207
|
+
task = asyncio.create_task(app(scope, to_app.get, from_app.put))
|
|
208
|
+
await to_app.put({"type": "lifespan.startup"})
|
|
209
|
+
started = await asyncio.wait_for(from_app.get(), timeout=5)
|
|
210
|
+
assert started == {"type": "lifespan.startup.complete"}
|
|
211
|
+
try:
|
|
212
|
+
yield
|
|
213
|
+
finally:
|
|
214
|
+
await to_app.put({"type": "lifespan.shutdown"})
|
|
215
|
+
stopped = await asyncio.wait_for(from_app.get(), timeout=5)
|
|
216
|
+
assert stopped == {"type": "lifespan.shutdown.complete"}
|
|
217
|
+
await asyncio.wait_for(task, timeout=5)
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
@asynccontextmanager
|
|
221
|
+
async def mcp_client_for_app(app, path="/-/mcp", cookies=None):
|
|
222
|
+
async with httpx2.AsyncClient(
|
|
223
|
+
transport=httpx2.ASGITransport(app=app),
|
|
224
|
+
base_url="http://localhost",
|
|
225
|
+
cookies=cookies,
|
|
226
|
+
) as http_client:
|
|
227
|
+
transport = streamable_http_client(
|
|
228
|
+
f"http://localhost{path}",
|
|
229
|
+
http_client=http_client,
|
|
230
|
+
)
|
|
231
|
+
async with Client(transport, raise_exceptions=True) as client:
|
|
232
|
+
yield client
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
@asynccontextmanager
|
|
236
|
+
async def mcp_http_client(datasette, path="/-/mcp", cookies=None):
|
|
237
|
+
app = datasette.app()
|
|
238
|
+
async with run_asgi_lifespan(app):
|
|
239
|
+
async with mcp_client_for_app(
|
|
240
|
+
app,
|
|
241
|
+
path=path,
|
|
242
|
+
cookies=cookies,
|
|
243
|
+
) as client:
|
|
244
|
+
yield client
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
@pytest.mark.asyncio
|
|
248
|
+
async def test_empty_database_has_empty_schema(tmp_path):
|
|
249
|
+
database_path = tmp_path / "empty.db"
|
|
250
|
+
database_path.touch()
|
|
251
|
+
datasette = Datasette([str(database_path)])
|
|
252
|
+
|
|
253
|
+
async with Client(create_mcp_server(datasette)) as client:
|
|
254
|
+
result = await client.call_tool("get_database_schema", {"database": "empty"})
|
|
255
|
+
|
|
256
|
+
assert result.structured_content == {"database": "empty", "schema": ""}
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
@pytest.mark.asyncio
|
|
260
|
+
async def test_query_results_are_truncated_at_datasette_limit(tmp_path):
|
|
261
|
+
database_path = tmp_path / "limited.db"
|
|
262
|
+
database_path.touch()
|
|
263
|
+
datasette = Datasette(
|
|
264
|
+
[str(database_path)],
|
|
265
|
+
settings={"max_returned_rows": 1},
|
|
266
|
+
)
|
|
267
|
+
|
|
268
|
+
async with Client(create_mcp_server(datasette)) as client:
|
|
269
|
+
result = await client.call_tool(
|
|
270
|
+
"execute_sql",
|
|
271
|
+
{
|
|
272
|
+
"database": "limited",
|
|
273
|
+
"sql": "select 1 as value union all select 2",
|
|
274
|
+
},
|
|
275
|
+
)
|
|
276
|
+
|
|
277
|
+
assert result.structured_content == {
|
|
278
|
+
"database": "limited",
|
|
279
|
+
"columns": ["value"],
|
|
280
|
+
"rows": [[1]],
|
|
281
|
+
"truncated": True,
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
@pytest.mark.asyncio
|
|
286
|
+
async def test_missing_and_internal_databases_are_not_disclosed(datasette):
|
|
287
|
+
async with Client(create_mcp_server(datasette)) as client:
|
|
288
|
+
missing = await client.call_tool("get_database_schema", {"database": "missing"})
|
|
289
|
+
internal = await client.call_tool(
|
|
290
|
+
"get_database_schema", {"database": "_internal"}
|
|
291
|
+
)
|
|
292
|
+
|
|
293
|
+
expected = "does not exist or is not available"
|
|
294
|
+
assert expected in tool_error_text(missing)
|
|
295
|
+
assert expected in tool_error_text(internal)
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
@pytest.mark.asyncio
|
|
299
|
+
async def test_database_visibility_permission_filters_list_and_schema(tmp_path):
|
|
300
|
+
database_path = tmp_path / "private.db"
|
|
301
|
+
database_path.touch()
|
|
302
|
+
datasette = Datasette(
|
|
303
|
+
[str(database_path)],
|
|
304
|
+
metadata={
|
|
305
|
+
"databases": {
|
|
306
|
+
"private": {
|
|
307
|
+
"allow": {"id": "allowed"},
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
},
|
|
311
|
+
)
|
|
312
|
+
|
|
313
|
+
async with Client(create_mcp_server(datasette)) as client:
|
|
314
|
+
databases = await client.call_tool("list_databases")
|
|
315
|
+
schema = await client.call_tool("get_database_schema", {"database": "private"})
|
|
316
|
+
|
|
317
|
+
assert databases.structured_content == {"databases": []}
|
|
318
|
+
assert "does not exist or is not available" in tool_error_text(schema)
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
@pytest.mark.asyncio
|
|
322
|
+
async def test_execute_sql_permission_is_enforced(tmp_path):
|
|
323
|
+
database_path = tmp_path / "restricted.db"
|
|
324
|
+
database_path.touch()
|
|
325
|
+
datasette = Datasette(
|
|
326
|
+
[str(database_path)],
|
|
327
|
+
settings={"default_allow_sql": False},
|
|
328
|
+
)
|
|
329
|
+
|
|
330
|
+
async with Client(create_mcp_server(datasette)) as client:
|
|
331
|
+
result = await client.call_tool(
|
|
332
|
+
"execute_sql",
|
|
333
|
+
{"database": "restricted", "sql": "select 1"},
|
|
334
|
+
)
|
|
335
|
+
|
|
336
|
+
assert (
|
|
337
|
+
"You do not have permission to execute SQL against database 'restricted'."
|
|
338
|
+
in tool_error_text(result)
|
|
339
|
+
)
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
@pytest.mark.parametrize(
|
|
343
|
+
"sql",
|
|
344
|
+
(
|
|
345
|
+
"insert into authors(name) values ('Katherine')",
|
|
346
|
+
"update authors set name = 'Katherine' where id = 1",
|
|
347
|
+
"delete from authors",
|
|
348
|
+
"create table forbidden(id integer)",
|
|
349
|
+
"drop table authors",
|
|
350
|
+
"alter table authors add column forbidden integer",
|
|
351
|
+
"replace into authors(id, name) values (1, 'Katherine')",
|
|
352
|
+
"attach database ':memory:' as forbidden",
|
|
353
|
+
"detach database forbidden",
|
|
354
|
+
"begin",
|
|
355
|
+
"pragma user_version = 1",
|
|
356
|
+
),
|
|
357
|
+
)
|
|
358
|
+
@pytest.mark.asyncio
|
|
359
|
+
async def test_execute_sql_rejects_non_read_only_operations(mcp_server, sql):
|
|
360
|
+
async with Client(mcp_server) as client:
|
|
361
|
+
result = await client.call_tool(
|
|
362
|
+
"execute_sql",
|
|
363
|
+
{"database": "test", "sql": sql},
|
|
364
|
+
)
|
|
365
|
+
|
|
366
|
+
assert "Statement must be a SELECT" in tool_error_text(result)
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
@pytest.mark.asyncio
|
|
370
|
+
async def test_execute_sql_rejects_multiple_statements(mcp_server):
|
|
371
|
+
async with Client(mcp_server) as client:
|
|
372
|
+
result = await client.call_tool(
|
|
373
|
+
"execute_sql",
|
|
374
|
+
{"database": "test", "sql": "select 1; select 2"},
|
|
375
|
+
)
|
|
376
|
+
|
|
377
|
+
assert "one statement at a time" in tool_error_text(result)
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
@pytest.mark.parametrize("sql", ("", " -- no statement\n"))
|
|
381
|
+
@pytest.mark.asyncio
|
|
382
|
+
async def test_execute_sql_rejects_missing_statement(mcp_server, sql):
|
|
383
|
+
async with Client(mcp_server) as client:
|
|
384
|
+
result = await client.call_tool(
|
|
385
|
+
"execute_sql",
|
|
386
|
+
{"database": "test", "sql": sql},
|
|
387
|
+
)
|
|
388
|
+
|
|
389
|
+
assert "Statement must be a SELECT" in tool_error_text(result)
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
@pytest.mark.asyncio
|
|
393
|
+
async def test_execute_sql_rejects_non_select_on_memory_database():
|
|
394
|
+
datasette = Datasette(memory=True)
|
|
395
|
+
|
|
396
|
+
async with Client(create_mcp_server(datasette)) as client:
|
|
397
|
+
rejected = await client.call_tool(
|
|
398
|
+
"execute_sql",
|
|
399
|
+
{
|
|
400
|
+
"database": "_memory",
|
|
401
|
+
"sql": "create table forbidden(id integer)",
|
|
402
|
+
},
|
|
403
|
+
)
|
|
404
|
+
subsequent_read = await client.call_tool(
|
|
405
|
+
"execute_sql",
|
|
406
|
+
{"database": "_memory", "sql": "select 1 as value"},
|
|
407
|
+
)
|
|
408
|
+
|
|
409
|
+
assert "Statement must be a SELECT" in tool_error_text(rejected)
|
|
410
|
+
assert subsequent_read.structured_content == {
|
|
411
|
+
"database": "_memory",
|
|
412
|
+
"columns": ["value"],
|
|
413
|
+
"rows": [[1]],
|
|
414
|
+
"truncated": False,
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
|
|
418
|
+
@pytest.mark.asyncio
|
|
419
|
+
async def test_mcp_streamable_http_endpoint(datasette):
|
|
420
|
+
async with mcp_http_client(datasette) as client:
|
|
421
|
+
tools = await client.list_tools()
|
|
422
|
+
query = await client.call_tool(
|
|
423
|
+
"execute_sql",
|
|
424
|
+
{"database": "test", "sql": "select name from authors order by id"},
|
|
425
|
+
)
|
|
426
|
+
|
|
427
|
+
assert [tool.name for tool in tools.tools] == [
|
|
428
|
+
"list_databases",
|
|
429
|
+
"get_database_schema",
|
|
430
|
+
"execute_sql",
|
|
431
|
+
]
|
|
432
|
+
assert query.structured_content["rows"] == [["ADA"], ["GRACE"]]
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
@pytest.mark.asyncio
|
|
436
|
+
async def test_mcp_endpoint_honors_datasette_base_url(tmp_path):
|
|
437
|
+
database_path = tmp_path / "prefixed.db"
|
|
438
|
+
database_path.touch()
|
|
439
|
+
datasette = Datasette(
|
|
440
|
+
[str(database_path)],
|
|
441
|
+
settings={"base_url": "/prefix/"},
|
|
442
|
+
)
|
|
443
|
+
|
|
444
|
+
async with mcp_http_client(datasette, path="/prefix/-/mcp") as client:
|
|
445
|
+
result = await client.call_tool("list_databases")
|
|
446
|
+
|
|
447
|
+
assert result.structured_content == {"databases": ["prefixed"]}
|
|
448
|
+
|
|
449
|
+
|
|
450
|
+
def test_csrf_exemption_matches_only_the_mcp_endpoint():
|
|
451
|
+
datasette = Datasette(
|
|
452
|
+
memory=True,
|
|
453
|
+
settings={"base_url": "/prefix/"},
|
|
454
|
+
)
|
|
455
|
+
|
|
456
|
+
assert skip_csrf(datasette, {"path": "/prefix/-/mcp", "method": "POST"}) is True
|
|
457
|
+
assert skip_csrf(datasette, {"path": "/prefix/-/mcp", "method": "DELETE"}) is True
|
|
458
|
+
assert (
|
|
459
|
+
skip_csrf(datasette, {"path": "/prefix/-/mcp/extra", "method": "POST"}) is False
|
|
460
|
+
)
|
|
461
|
+
assert skip_csrf(datasette, {"path": "/prefix/-/mcp", "method": "GET"}) is False
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
@pytest.mark.asyncio
|
|
465
|
+
async def test_http_actor_is_used_for_database_permissions(tmp_path):
|
|
466
|
+
database_path = tmp_path / "private.db"
|
|
467
|
+
database_path.touch()
|
|
468
|
+
datasette = Datasette(
|
|
469
|
+
[str(database_path)],
|
|
470
|
+
metadata={
|
|
471
|
+
"databases": {
|
|
472
|
+
"private": {
|
|
473
|
+
"allow": {"id": "allowed"},
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
},
|
|
477
|
+
)
|
|
478
|
+
actor_cookie = datasette.sign({"a": {"id": "allowed"}}, "actor")
|
|
479
|
+
|
|
480
|
+
app = datasette.app()
|
|
481
|
+
async with run_asgi_lifespan(app):
|
|
482
|
+
async with mcp_client_for_app(app) as anonymous_client:
|
|
483
|
+
anonymous = await anonymous_client.call_tool("list_databases")
|
|
484
|
+
async with mcp_client_for_app(
|
|
485
|
+
app,
|
|
486
|
+
cookies={"ds_actor": actor_cookie},
|
|
487
|
+
) as allowed_client:
|
|
488
|
+
allowed = await allowed_client.call_tool("list_databases")
|
|
489
|
+
|
|
490
|
+
assert anonymous.structured_content == {"databases": []}
|
|
491
|
+
assert allowed.structured_content == {"databases": ["private"]}
|
|
492
|
+
|
|
493
|
+
|
|
494
|
+
@pytest.mark.asyncio
|
|
495
|
+
async def test_mcp_session_manager_runs_once_per_asgi_lifespan(
|
|
496
|
+
datasette,
|
|
497
|
+
monkeypatch,
|
|
498
|
+
):
|
|
499
|
+
starts = 0
|
|
500
|
+
stops = 0
|
|
501
|
+
original_run = StreamableHTTPSessionManager.run
|
|
502
|
+
|
|
503
|
+
@asynccontextmanager
|
|
504
|
+
async def counted_run(manager):
|
|
505
|
+
nonlocal starts, stops
|
|
506
|
+
starts += 1
|
|
507
|
+
async with original_run(manager):
|
|
508
|
+
yield
|
|
509
|
+
stops += 1
|
|
510
|
+
|
|
511
|
+
monkeypatch.setattr(StreamableHTTPSessionManager, "run", counted_run)
|
|
512
|
+
|
|
513
|
+
async with mcp_http_client(datasette) as client:
|
|
514
|
+
await client.call_tool("list_databases")
|
|
515
|
+
await client.call_tool("list_databases")
|
|
516
|
+
|
|
517
|
+
assert starts == 1
|
|
518
|
+
assert stops == 1
|