quantdinger-mcp 0.1.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.
@@ -0,0 +1,203 @@
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 [quantdinger.com] [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.
202
+
203
+
@@ -0,0 +1,133 @@
1
+ Metadata-Version: 2.4
2
+ Name: quantdinger-mcp
3
+ Version: 0.1.0
4
+ Summary: Model Context Protocol (MCP) server for the QuantDinger Agent Gateway — exposes market data, strategies, backtests and paper trading to AI agents (Cursor, Claude Code, Codex, OpenClaw, NanoBot, ...).
5
+ Author-email: QuantDinger <quantdinger@gmail.com>
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/brokermr810/QuantDinger
8
+ Project-URL: Documentation, https://github.com/brokermr810/QuantDinger/blob/main/docs/agent/AGENT_QUICKSTART.md
9
+ Project-URL: Repository, https://github.com/brokermr810/QuantDinger
10
+ Project-URL: Issues, https://github.com/brokermr810/QuantDinger/issues
11
+ Project-URL: Changelog, https://github.com/brokermr810/QuantDinger/blob/main/docs/CHANGELOG.md
12
+ Keywords: mcp,model-context-protocol,quantdinger,ai-agent,trading,backtest,quant,cursor,claude,codex,openclaw,nanobot
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Intended Audience :: Financial and Insurance Industry
16
+ Classifier: License :: OSI Approved :: Apache Software License
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Topic :: Office/Business :: Financial :: Investment
24
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
25
+ Requires-Python: >=3.10
26
+ Description-Content-Type: text/markdown
27
+ License-File: LICENSE
28
+ Requires-Dist: mcp>=1.2.0
29
+ Requires-Dist: httpx>=0.27.0
30
+ Provides-Extra: dev
31
+ Requires-Dist: pytest>=7; extra == "dev"
32
+ Requires-Dist: build>=1.0; extra == "dev"
33
+ Requires-Dist: twine>=4; extra == "dev"
34
+ Dynamic: license-file
35
+
36
+ # QuantDinger MCP server
37
+
38
+ Thin Model Context Protocol server that exposes a curated subset of the
39
+ QuantDinger Agent Gateway (`/api/agent/v1`) as MCP tools, so AI clients
40
+ that support MCP (Cursor, Claude-style desktop apps, etc.) can drive
41
+ QuantDinger without writing custom HTTP code.
42
+
43
+ This package is an **additive** integration. The Agent Gateway REST API
44
+ remains the source of truth.
45
+
46
+ ## What it exposes
47
+
48
+ Read-class (R) and Backtest-class (B) tools only — no live trading from
49
+ MCP. Use the REST `/api/agent/v1/quick-trade/...` endpoints if/when you
50
+ explicitly enable trading for an agent.
51
+
52
+ | Tool | Class | Purpose |
53
+ |------|-------|---------|
54
+ | `whoami` | R | Inspect the calling token |
55
+ | `list_markets` | R | Markets the token may query |
56
+ | `search_symbols` | R | Symbols within a market |
57
+ | `get_klines` | R | OHLCV bars |
58
+ | `get_price` | R | Latest price |
59
+ | `list_strategies` | R | Tenant's strategies |
60
+ | `get_strategy` | R | One strategy |
61
+ | `submit_backtest` | B | Queue a backtest |
62
+ | `get_job` | R | Poll a job |
63
+ | `regime_detect` | B | Synchronous regime detection |
64
+ | `submit_structured_tune` | B | Queue grid/random tuning |
65
+
66
+ ## Install (editable)
67
+
68
+ ```bash
69
+ cd mcp_server
70
+ pip install -e .
71
+ ```
72
+
73
+ ## Run
74
+
75
+ Configuration is env-only so the same binary works in desktop and cloud.
76
+
77
+ | Variable | Required | Purpose |
78
+ |----------|----------|---------|
79
+ | `QUANTDINGER_BASE_URL` | yes | e.g. `http://localhost:8888` |
80
+ | `QUANTDINGER_AGENT_TOKEN` | yes | a token issued via `/api/agent/v1/admin/tokens` |
81
+ | `QUANTDINGER_MCP_TRANSPORT`| no | `stdio` (default), `sse`, or `streamable-http` |
82
+ | `QUANTDINGER_MCP_HOST` | no | bind host for HTTP transports (default `127.0.0.1`) |
83
+ | `QUANTDINGER_MCP_PORT` | no | bind port for HTTP transports (default `8000`) |
84
+ | `QUANTDINGER_TIMEOUT_S` | no | upstream HTTP timeout (default `60`) |
85
+
86
+ ### stdio (desktop IDEs)
87
+
88
+ ```bash
89
+ QUANTDINGER_BASE_URL=http://localhost:8888 \
90
+ QUANTDINGER_AGENT_TOKEN=qd_agent_xxxxx \
91
+ quantdinger-mcp
92
+ ```
93
+
94
+ ### SSE / Streamable HTTP (cloud agents, remote IDEs)
95
+
96
+ ```bash
97
+ QUANTDINGER_BASE_URL=http://localhost:8888 \
98
+ QUANTDINGER_AGENT_TOKEN=qd_agent_xxxxx \
99
+ QUANTDINGER_MCP_TRANSPORT=streamable-http \
100
+ QUANTDINGER_MCP_HOST=0.0.0.0 \
101
+ QUANTDINGER_MCP_PORT=7800 \
102
+ quantdinger-mcp
103
+ ```
104
+
105
+ The server is then reachable at `http://<host>:7800/`. Use `sse` instead of
106
+ `streamable-http` for clients that only support the older SSE transport.
107
+
108
+ ## Wire into a client
109
+
110
+ ### Local stdio client config
111
+
112
+ ```json
113
+ {
114
+ "mcpServers": {
115
+ "quantdinger": {
116
+ "command": "quantdinger-mcp",
117
+ "env": {
118
+ "QUANTDINGER_BASE_URL": "http://localhost:8888",
119
+ "QUANTDINGER_AGENT_TOKEN": "qd_agent_xxxxxxxx"
120
+ }
121
+ }
122
+ }
123
+ }
124
+ ```
125
+
126
+ ### Remote HTTP client config
127
+
128
+ For clients that connect to an MCP server over HTTP/SSE rather than spawning
129
+ a subprocess, point them at the URL the server is bound to (e.g.
130
+ `http://your-host:7800`) and let the client handle protocol negotiation.
131
+
132
+ Never put production exchange keys or admin JWTs in the MCP config — only
133
+ agent tokens, scoped to the capabilities the client actually needs.
@@ -0,0 +1,98 @@
1
+ # QuantDinger MCP server
2
+
3
+ Thin Model Context Protocol server that exposes a curated subset of the
4
+ QuantDinger Agent Gateway (`/api/agent/v1`) as MCP tools, so AI clients
5
+ that support MCP (Cursor, Claude-style desktop apps, etc.) can drive
6
+ QuantDinger without writing custom HTTP code.
7
+
8
+ This package is an **additive** integration. The Agent Gateway REST API
9
+ remains the source of truth.
10
+
11
+ ## What it exposes
12
+
13
+ Read-class (R) and Backtest-class (B) tools only — no live trading from
14
+ MCP. Use the REST `/api/agent/v1/quick-trade/...` endpoints if/when you
15
+ explicitly enable trading for an agent.
16
+
17
+ | Tool | Class | Purpose |
18
+ |------|-------|---------|
19
+ | `whoami` | R | Inspect the calling token |
20
+ | `list_markets` | R | Markets the token may query |
21
+ | `search_symbols` | R | Symbols within a market |
22
+ | `get_klines` | R | OHLCV bars |
23
+ | `get_price` | R | Latest price |
24
+ | `list_strategies` | R | Tenant's strategies |
25
+ | `get_strategy` | R | One strategy |
26
+ | `submit_backtest` | B | Queue a backtest |
27
+ | `get_job` | R | Poll a job |
28
+ | `regime_detect` | B | Synchronous regime detection |
29
+ | `submit_structured_tune` | B | Queue grid/random tuning |
30
+
31
+ ## Install (editable)
32
+
33
+ ```bash
34
+ cd mcp_server
35
+ pip install -e .
36
+ ```
37
+
38
+ ## Run
39
+
40
+ Configuration is env-only so the same binary works in desktop and cloud.
41
+
42
+ | Variable | Required | Purpose |
43
+ |----------|----------|---------|
44
+ | `QUANTDINGER_BASE_URL` | yes | e.g. `http://localhost:8888` |
45
+ | `QUANTDINGER_AGENT_TOKEN` | yes | a token issued via `/api/agent/v1/admin/tokens` |
46
+ | `QUANTDINGER_MCP_TRANSPORT`| no | `stdio` (default), `sse`, or `streamable-http` |
47
+ | `QUANTDINGER_MCP_HOST` | no | bind host for HTTP transports (default `127.0.0.1`) |
48
+ | `QUANTDINGER_MCP_PORT` | no | bind port for HTTP transports (default `8000`) |
49
+ | `QUANTDINGER_TIMEOUT_S` | no | upstream HTTP timeout (default `60`) |
50
+
51
+ ### stdio (desktop IDEs)
52
+
53
+ ```bash
54
+ QUANTDINGER_BASE_URL=http://localhost:8888 \
55
+ QUANTDINGER_AGENT_TOKEN=qd_agent_xxxxx \
56
+ quantdinger-mcp
57
+ ```
58
+
59
+ ### SSE / Streamable HTTP (cloud agents, remote IDEs)
60
+
61
+ ```bash
62
+ QUANTDINGER_BASE_URL=http://localhost:8888 \
63
+ QUANTDINGER_AGENT_TOKEN=qd_agent_xxxxx \
64
+ QUANTDINGER_MCP_TRANSPORT=streamable-http \
65
+ QUANTDINGER_MCP_HOST=0.0.0.0 \
66
+ QUANTDINGER_MCP_PORT=7800 \
67
+ quantdinger-mcp
68
+ ```
69
+
70
+ The server is then reachable at `http://<host>:7800/`. Use `sse` instead of
71
+ `streamable-http` for clients that only support the older SSE transport.
72
+
73
+ ## Wire into a client
74
+
75
+ ### Local stdio client config
76
+
77
+ ```json
78
+ {
79
+ "mcpServers": {
80
+ "quantdinger": {
81
+ "command": "quantdinger-mcp",
82
+ "env": {
83
+ "QUANTDINGER_BASE_URL": "http://localhost:8888",
84
+ "QUANTDINGER_AGENT_TOKEN": "qd_agent_xxxxxxxx"
85
+ }
86
+ }
87
+ }
88
+ }
89
+ ```
90
+
91
+ ### Remote HTTP client config
92
+
93
+ For clients that connect to an MCP server over HTTP/SSE rather than spawning
94
+ a subprocess, point them at the URL the server is bound to (e.g.
95
+ `http://your-host:7800`) and let the client handle protocol negotiation.
96
+
97
+ Never put production exchange keys or admin JWTs in the MCP config — only
98
+ agent tokens, scoped to the capabilities the client actually needs.
@@ -0,0 +1,70 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "quantdinger-mcp"
7
+ version = "0.1.0"
8
+ description = "Model Context Protocol (MCP) server for the QuantDinger Agent Gateway — exposes market data, strategies, backtests and paper trading to AI agents (Cursor, Claude Code, Codex, OpenClaw, NanoBot, ...)."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = { text = "Apache-2.0" }
12
+ authors = [
13
+ { name = "QuantDinger", email = "quantdinger@gmail.com" }
14
+ ]
15
+ keywords = [
16
+ "mcp",
17
+ "model-context-protocol",
18
+ "quantdinger",
19
+ "ai-agent",
20
+ "trading",
21
+ "backtest",
22
+ "quant",
23
+ "cursor",
24
+ "claude",
25
+ "codex",
26
+ "openclaw",
27
+ "nanobot"
28
+ ]
29
+ classifiers = [
30
+ "Development Status :: 4 - Beta",
31
+ "Intended Audience :: Developers",
32
+ "Intended Audience :: Financial and Insurance Industry",
33
+ "License :: OSI Approved :: Apache Software License",
34
+ "Operating System :: OS Independent",
35
+ "Programming Language :: Python :: 3",
36
+ "Programming Language :: Python :: 3.10",
37
+ "Programming Language :: Python :: 3.11",
38
+ "Programming Language :: Python :: 3.12",
39
+ "Programming Language :: Python :: 3.13",
40
+ "Topic :: Office/Business :: Financial :: Investment",
41
+ "Topic :: Software Development :: Libraries :: Python Modules"
42
+ ]
43
+ dependencies = [
44
+ "mcp>=1.2.0",
45
+ "httpx>=0.27.0"
46
+ ]
47
+
48
+ [project.optional-dependencies]
49
+ dev = [
50
+ "pytest>=7",
51
+ "build>=1.0",
52
+ "twine>=4"
53
+ ]
54
+
55
+ [project.urls]
56
+ Homepage = "https://github.com/brokermr810/QuantDinger"
57
+ Documentation = "https://github.com/brokermr810/QuantDinger/blob/main/docs/agent/AGENT_QUICKSTART.md"
58
+ Repository = "https://github.com/brokermr810/QuantDinger"
59
+ Issues = "https://github.com/brokermr810/QuantDinger/issues"
60
+ Changelog = "https://github.com/brokermr810/QuantDinger/blob/main/docs/CHANGELOG.md"
61
+
62
+ [project.scripts]
63
+ quantdinger-mcp = "quantdinger_mcp.server:main"
64
+
65
+ [tool.setuptools]
66
+ include-package-data = true
67
+ license-files = ["LICENSE"]
68
+
69
+ [tool.setuptools.packages.find]
70
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,2 @@
1
+ """QuantDinger MCP server package."""
2
+ __version__ = "0.1.0"
@@ -0,0 +1,305 @@
1
+ """
2
+ QuantDinger MCP server — exposes the Agent Gateway as MCP tools.
3
+
4
+ This is intentionally a thin wrapper:
5
+ * REST stays the source of truth (`/api/agent/v1`).
6
+ * Only Read-class (R) and Backtest-class (B) tools are exposed.
7
+ * The user-supplied agent token's scopes still gate every call server-side.
8
+
9
+ If you want to expose more (e.g. trading), prefer issuing a token with the
10
+ right scopes and keep this server unchanged — that way the security boundary
11
+ stays in the Gateway, not in the MCP layer.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import os
16
+ import sys
17
+ from typing import Any
18
+
19
+ import httpx
20
+ from mcp.server.fastmcp import FastMCP
21
+
22
+
23
+ def _env(name: str, required: bool = True) -> str:
24
+ value = (os.environ.get(name) or "").strip()
25
+ if not value and required:
26
+ print(
27
+ f"[quantdinger-mcp] missing required env var: {name}",
28
+ file=sys.stderr,
29
+ )
30
+ sys.exit(2)
31
+ return value
32
+
33
+
34
+ BASE_URL = _env("QUANTDINGER_BASE_URL").rstrip("/")
35
+ AGENT_TOKEN = _env("QUANTDINGER_AGENT_TOKEN")
36
+ TIMEOUT_S = float(os.environ.get("QUANTDINGER_TIMEOUT_S", "60"))
37
+
38
+
39
+ _client = httpx.Client(
40
+ base_url=BASE_URL,
41
+ timeout=TIMEOUT_S,
42
+ headers={"Authorization": f"Bearer {AGENT_TOKEN}"},
43
+ )
44
+
45
+
46
+ def _get(path: str, params: dict | None = None) -> Any:
47
+ r = _client.get(path, params=params or {})
48
+ return _unwrap(r)
49
+
50
+
51
+ def _post(path: str, json: dict | None = None, headers: dict | None = None) -> Any:
52
+ r = _client.post(path, json=json or {}, headers=headers or {})
53
+ return _unwrap(r)
54
+
55
+
56
+ def _unwrap(r: httpx.Response) -> Any:
57
+ try:
58
+ body = r.json()
59
+ except Exception:
60
+ return {
61
+ "error": True,
62
+ "status": r.status_code,
63
+ "text": r.text[:2000],
64
+ }
65
+ if r.status_code >= 400:
66
+ return {
67
+ "error": True,
68
+ "status": r.status_code,
69
+ "body": body,
70
+ }
71
+ if isinstance(body, dict) and "data" in body:
72
+ return body["data"]
73
+ return body
74
+
75
+
76
+ mcp = FastMCP(
77
+ "quantdinger",
78
+ instructions=(
79
+ "Tools for the QuantDinger self-hosted quant platform. "
80
+ "All tools are tenant-scoped via the configured agent token. "
81
+ "Trading is intentionally NOT exposed via MCP; use the REST API for that."
82
+ ),
83
+ )
84
+
85
+
86
+ # ───────────────────────────── Read-class tools ─────────────────────────────
87
+
88
+ @mcp.tool()
89
+ def whoami() -> Any:
90
+ """Return the calling token's identity, scopes, and allowlists."""
91
+ return _get("/api/agent/v1/whoami")
92
+
93
+
94
+ @mcp.tool()
95
+ def list_markets() -> Any:
96
+ """List markets the configured token is allowed to query."""
97
+ return _get("/api/agent/v1/markets")
98
+
99
+
100
+ @mcp.tool()
101
+ def search_symbols(market: str, keyword: str = "", limit: int = 20) -> Any:
102
+ """Find symbols in a market.
103
+
104
+ Args:
105
+ market: Market id, e.g. "Crypto", "USStock", "Forex".
106
+ keyword: Substring/code; empty returns hot symbols.
107
+ limit: 1..100, default 20.
108
+ """
109
+ return _get(
110
+ f"/api/agent/v1/markets/{market}/symbols",
111
+ params={"keyword": keyword, "limit": limit},
112
+ )
113
+
114
+
115
+ @mcp.tool()
116
+ def get_klines(
117
+ market: str,
118
+ symbol: str,
119
+ timeframe: str = "1D",
120
+ limit: int = 300,
121
+ before_time: int | None = None,
122
+ ) -> Any:
123
+ """OHLCV bars.
124
+
125
+ Args:
126
+ market: e.g. "Crypto"
127
+ symbol: e.g. "BTC/USDT"
128
+ timeframe: "1m"/"5m"/"15m"/"30m"/"1H"/"4H"/"1D"/"1W"
129
+ limit: 1..2000
130
+ before_time: unix seconds; for paging older bars.
131
+ """
132
+ params = {"market": market, "symbol": symbol, "timeframe": timeframe, "limit": limit}
133
+ if before_time is not None:
134
+ params["before_time"] = int(before_time)
135
+ return _get("/api/agent/v1/klines", params=params)
136
+
137
+
138
+ @mcp.tool()
139
+ def get_price(market: str, symbol: str) -> Any:
140
+ """Latest price for a symbol."""
141
+ return _get("/api/agent/v1/price", params={"market": market, "symbol": symbol})
142
+
143
+
144
+ @mcp.tool()
145
+ def list_strategies(limit: int = 50) -> Any:
146
+ """List the tenant's strategies (compact projection)."""
147
+ return _get("/api/agent/v1/strategies", params={"limit": limit})
148
+
149
+
150
+ @mcp.tool()
151
+ def get_strategy(strategy_id: int) -> Any:
152
+ """Get a strategy by id (tenant-scoped)."""
153
+ return _get(f"/api/agent/v1/strategies/{int(strategy_id)}")
154
+
155
+
156
+ @mcp.tool()
157
+ def get_job(job_id: str) -> Any:
158
+ """Poll a previously-submitted backtest / experiment job."""
159
+ return _get(f"/api/agent/v1/jobs/{job_id}")
160
+
161
+
162
+ @mcp.tool()
163
+ def list_jobs(kind: str | None = None, limit: int = 50) -> Any:
164
+ """List recent jobs for this tenant. Optional `kind` filter."""
165
+ params: dict[str, Any] = {"limit": limit}
166
+ if kind:
167
+ params["kind"] = kind
168
+ return _get("/api/agent/v1/jobs", params=params)
169
+
170
+
171
+ # ───────────────────────────── Backtest-class tools ─────────────────────────────
172
+
173
+ @mcp.tool()
174
+ def submit_backtest(
175
+ code: str,
176
+ market: str,
177
+ symbol: str,
178
+ timeframe: str,
179
+ start_date: str,
180
+ end_date: str,
181
+ initial_capital: float = 10000,
182
+ commission: float = 0.001,
183
+ slippage: float = 0.0,
184
+ leverage: int = 1,
185
+ trade_direction: str = "long",
186
+ idempotency_key: str | None = None,
187
+ ) -> Any:
188
+ """Submit a backtest. Returns `{job_id, status, ...}` — poll with `get_job`.
189
+
190
+ Args:
191
+ code: Indicator code (Python).
192
+ market/symbol/timeframe: Series identification.
193
+ start_date/end_date: YYYY-MM-DD.
194
+ initial_capital, commission, slippage, leverage, trade_direction:
195
+ standard backtest knobs.
196
+ idempotency_key: optional; repeat calls with the same key return the
197
+ original job instead of submitting a duplicate.
198
+ """
199
+ payload = {
200
+ "code": code,
201
+ "market": market,
202
+ "symbol": symbol,
203
+ "timeframe": timeframe,
204
+ "start_date": start_date,
205
+ "end_date": end_date,
206
+ "initial_capital": initial_capital,
207
+ "commission": commission,
208
+ "slippage": slippage,
209
+ "leverage": leverage,
210
+ "trade_direction": trade_direction,
211
+ }
212
+ headers = {"Idempotency-Key": idempotency_key} if idempotency_key else None
213
+ return _post("/api/agent/v1/backtests", json=payload, headers=headers)
214
+
215
+
216
+ @mcp.tool()
217
+ def regime_detect(
218
+ market: str,
219
+ symbol: str,
220
+ timeframe: str,
221
+ start_date: str,
222
+ end_date: str,
223
+ ) -> Any:
224
+ """Detect the current market regime (synchronous)."""
225
+ return _post(
226
+ "/api/agent/v1/experiments/regime/detect",
227
+ json={
228
+ "market": market, "symbol": symbol, "timeframe": timeframe,
229
+ "startDate": start_date, "endDate": end_date,
230
+ },
231
+ )
232
+
233
+
234
+ @mcp.tool()
235
+ def submit_structured_tune(payload: dict) -> Any:
236
+ """Submit a grid/random tuning job. Returns a job for polling.
237
+
238
+ `payload` should include `base` (a backtest spec) and either `parameterSpace`
239
+ (grid) or `randomTrials` (random). See `docs/AI_TRADING_SYSTEM_PLAN_CN.md`.
240
+ """
241
+ return _post("/api/agent/v1/experiments/structured-tune", json=payload)
242
+
243
+
244
+ _TRANSPORTS = {"stdio", "sse", "streamable-http"}
245
+
246
+
247
+ def _resolve_transport() -> str:
248
+ raw = (os.environ.get("QUANTDINGER_MCP_TRANSPORT") or "stdio").strip().lower()
249
+ # Accept a few obvious aliases so users don't have to look this up.
250
+ if raw in ("http", "streaming-http", "streamable_http"):
251
+ raw = "streamable-http"
252
+ if raw not in _TRANSPORTS:
253
+ print(
254
+ f"[quantdinger-mcp] unknown transport '{raw}'. "
255
+ f"Expected one of: {sorted(_TRANSPORTS)} (or http/streaming-http alias).",
256
+ file=sys.stderr,
257
+ )
258
+ sys.exit(2)
259
+ return raw
260
+
261
+
262
+ def _apply_http_settings_from_env() -> None:
263
+ """Bind host/port for HTTP transports without forcing a CLI dance.
264
+
265
+ FastMCP exposes these via its `settings` attribute. We only touch them when
266
+ the transport is HTTP-flavored, so the stdio default stays untouched.
267
+ """
268
+ host = (os.environ.get("QUANTDINGER_MCP_HOST") or "").strip()
269
+ port_raw = (os.environ.get("QUANTDINGER_MCP_PORT") or "").strip()
270
+ settings = getattr(mcp, "settings", None)
271
+ if settings is None:
272
+ return
273
+ if host:
274
+ try:
275
+ settings.host = host
276
+ except Exception:
277
+ pass
278
+ if port_raw:
279
+ try:
280
+ settings.port = int(port_raw)
281
+ except Exception:
282
+ print(
283
+ f"[quantdinger-mcp] invalid QUANTDINGER_MCP_PORT='{port_raw}', ignoring.",
284
+ file=sys.stderr,
285
+ )
286
+
287
+
288
+ def main() -> None:
289
+ """Entrypoint.
290
+
291
+ Transport selection (env-only — works in both desktop and cloud):
292
+ QUANTDINGER_MCP_TRANSPORT=stdio (default; stdin/stdout)
293
+ QUANTDINGER_MCP_TRANSPORT=sse (SSE over HTTP)
294
+ QUANTDINGER_MCP_TRANSPORT=streamable-http (newer MCP HTTP transport)
295
+ QUANTDINGER_MCP_HOST=0.0.0.0 (bind for HTTP transports)
296
+ QUANTDINGER_MCP_PORT=7800 (port for HTTP transports)
297
+ """
298
+ transport = _resolve_transport()
299
+ if transport in ("sse", "streamable-http"):
300
+ _apply_http_settings_from_env()
301
+ mcp.run(transport=transport)
302
+
303
+
304
+ if __name__ == "__main__":
305
+ main()
@@ -0,0 +1,133 @@
1
+ Metadata-Version: 2.4
2
+ Name: quantdinger-mcp
3
+ Version: 0.1.0
4
+ Summary: Model Context Protocol (MCP) server for the QuantDinger Agent Gateway — exposes market data, strategies, backtests and paper trading to AI agents (Cursor, Claude Code, Codex, OpenClaw, NanoBot, ...).
5
+ Author-email: QuantDinger <quantdinger@gmail.com>
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/brokermr810/QuantDinger
8
+ Project-URL: Documentation, https://github.com/brokermr810/QuantDinger/blob/main/docs/agent/AGENT_QUICKSTART.md
9
+ Project-URL: Repository, https://github.com/brokermr810/QuantDinger
10
+ Project-URL: Issues, https://github.com/brokermr810/QuantDinger/issues
11
+ Project-URL: Changelog, https://github.com/brokermr810/QuantDinger/blob/main/docs/CHANGELOG.md
12
+ Keywords: mcp,model-context-protocol,quantdinger,ai-agent,trading,backtest,quant,cursor,claude,codex,openclaw,nanobot
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Intended Audience :: Financial and Insurance Industry
16
+ Classifier: License :: OSI Approved :: Apache Software License
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Topic :: Office/Business :: Financial :: Investment
24
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
25
+ Requires-Python: >=3.10
26
+ Description-Content-Type: text/markdown
27
+ License-File: LICENSE
28
+ Requires-Dist: mcp>=1.2.0
29
+ Requires-Dist: httpx>=0.27.0
30
+ Provides-Extra: dev
31
+ Requires-Dist: pytest>=7; extra == "dev"
32
+ Requires-Dist: build>=1.0; extra == "dev"
33
+ Requires-Dist: twine>=4; extra == "dev"
34
+ Dynamic: license-file
35
+
36
+ # QuantDinger MCP server
37
+
38
+ Thin Model Context Protocol server that exposes a curated subset of the
39
+ QuantDinger Agent Gateway (`/api/agent/v1`) as MCP tools, so AI clients
40
+ that support MCP (Cursor, Claude-style desktop apps, etc.) can drive
41
+ QuantDinger without writing custom HTTP code.
42
+
43
+ This package is an **additive** integration. The Agent Gateway REST API
44
+ remains the source of truth.
45
+
46
+ ## What it exposes
47
+
48
+ Read-class (R) and Backtest-class (B) tools only — no live trading from
49
+ MCP. Use the REST `/api/agent/v1/quick-trade/...` endpoints if/when you
50
+ explicitly enable trading for an agent.
51
+
52
+ | Tool | Class | Purpose |
53
+ |------|-------|---------|
54
+ | `whoami` | R | Inspect the calling token |
55
+ | `list_markets` | R | Markets the token may query |
56
+ | `search_symbols` | R | Symbols within a market |
57
+ | `get_klines` | R | OHLCV bars |
58
+ | `get_price` | R | Latest price |
59
+ | `list_strategies` | R | Tenant's strategies |
60
+ | `get_strategy` | R | One strategy |
61
+ | `submit_backtest` | B | Queue a backtest |
62
+ | `get_job` | R | Poll a job |
63
+ | `regime_detect` | B | Synchronous regime detection |
64
+ | `submit_structured_tune` | B | Queue grid/random tuning |
65
+
66
+ ## Install (editable)
67
+
68
+ ```bash
69
+ cd mcp_server
70
+ pip install -e .
71
+ ```
72
+
73
+ ## Run
74
+
75
+ Configuration is env-only so the same binary works in desktop and cloud.
76
+
77
+ | Variable | Required | Purpose |
78
+ |----------|----------|---------|
79
+ | `QUANTDINGER_BASE_URL` | yes | e.g. `http://localhost:8888` |
80
+ | `QUANTDINGER_AGENT_TOKEN` | yes | a token issued via `/api/agent/v1/admin/tokens` |
81
+ | `QUANTDINGER_MCP_TRANSPORT`| no | `stdio` (default), `sse`, or `streamable-http` |
82
+ | `QUANTDINGER_MCP_HOST` | no | bind host for HTTP transports (default `127.0.0.1`) |
83
+ | `QUANTDINGER_MCP_PORT` | no | bind port for HTTP transports (default `8000`) |
84
+ | `QUANTDINGER_TIMEOUT_S` | no | upstream HTTP timeout (default `60`) |
85
+
86
+ ### stdio (desktop IDEs)
87
+
88
+ ```bash
89
+ QUANTDINGER_BASE_URL=http://localhost:8888 \
90
+ QUANTDINGER_AGENT_TOKEN=qd_agent_xxxxx \
91
+ quantdinger-mcp
92
+ ```
93
+
94
+ ### SSE / Streamable HTTP (cloud agents, remote IDEs)
95
+
96
+ ```bash
97
+ QUANTDINGER_BASE_URL=http://localhost:8888 \
98
+ QUANTDINGER_AGENT_TOKEN=qd_agent_xxxxx \
99
+ QUANTDINGER_MCP_TRANSPORT=streamable-http \
100
+ QUANTDINGER_MCP_HOST=0.0.0.0 \
101
+ QUANTDINGER_MCP_PORT=7800 \
102
+ quantdinger-mcp
103
+ ```
104
+
105
+ The server is then reachable at `http://<host>:7800/`. Use `sse` instead of
106
+ `streamable-http` for clients that only support the older SSE transport.
107
+
108
+ ## Wire into a client
109
+
110
+ ### Local stdio client config
111
+
112
+ ```json
113
+ {
114
+ "mcpServers": {
115
+ "quantdinger": {
116
+ "command": "quantdinger-mcp",
117
+ "env": {
118
+ "QUANTDINGER_BASE_URL": "http://localhost:8888",
119
+ "QUANTDINGER_AGENT_TOKEN": "qd_agent_xxxxxxxx"
120
+ }
121
+ }
122
+ }
123
+ }
124
+ ```
125
+
126
+ ### Remote HTTP client config
127
+
128
+ For clients that connect to an MCP server over HTTP/SSE rather than spawning
129
+ a subprocess, point them at the URL the server is bound to (e.g.
130
+ `http://your-host:7800`) and let the client handle protocol negotiation.
131
+
132
+ Never put production exchange keys or admin JWTs in the MCP config — only
133
+ agent tokens, scoped to the capabilities the client actually needs.
@@ -0,0 +1,12 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/quantdinger_mcp/__init__.py
5
+ src/quantdinger_mcp/server.py
6
+ src/quantdinger_mcp.egg-info/PKG-INFO
7
+ src/quantdinger_mcp.egg-info/SOURCES.txt
8
+ src/quantdinger_mcp.egg-info/dependency_links.txt
9
+ src/quantdinger_mcp.egg-info/entry_points.txt
10
+ src/quantdinger_mcp.egg-info/requires.txt
11
+ src/quantdinger_mcp.egg-info/top_level.txt
12
+ tests/test_transport_resolution.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ quantdinger-mcp = quantdinger_mcp.server:main
@@ -0,0 +1,7 @@
1
+ mcp>=1.2.0
2
+ httpx>=0.27.0
3
+
4
+ [dev]
5
+ pytest>=7
6
+ build>=1.0
7
+ twine>=4
@@ -0,0 +1 @@
1
+ quantdinger_mcp
@@ -0,0 +1,75 @@
1
+ """Bootstrap-only tests for the MCP server.
2
+
3
+ We don't run an actual MCP loop here — that requires stdio handshakes — but
4
+ we do verify that:
5
+
6
+ * Required env vars are validated up-front.
7
+ * The transport selector resolves common spellings without side effects.
8
+ * The HTTP-settings shim doesn't fail when the FastMCP `settings` shape
9
+ differs across versions (we feed it a dummy object).
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import importlib
14
+ import sys
15
+ from types import SimpleNamespace
16
+
17
+ import pytest
18
+
19
+ # The MCP SDK is an optional dependency for unit testing this package.
20
+ # Skip cleanly if the consumer hasn't installed it (e.g. backend-only CI).
21
+ pytest.importorskip("mcp")
22
+
23
+
24
+ @pytest.fixture
25
+ def fresh_module(monkeypatch):
26
+ """Reload the server module with the env preset so import-time checks pass."""
27
+ monkeypatch.setenv("QUANTDINGER_BASE_URL", "http://localhost:8888")
28
+ monkeypatch.setenv("QUANTDINGER_AGENT_TOKEN", "qd_agent_test_token")
29
+ sys.modules.pop("quantdinger_mcp.server", None)
30
+ # Make the package importable when the project hasn't been pip-installed.
31
+ pkg_root = sys.modules[__name__].__file__
32
+ import os
33
+ src_dir = os.path.normpath(os.path.join(os.path.dirname(pkg_root), "..", "src"))
34
+ if src_dir not in sys.path:
35
+ sys.path.insert(0, src_dir)
36
+ return importlib.import_module("quantdinger_mcp.server")
37
+
38
+
39
+ def test_transport_default_is_stdio(monkeypatch, fresh_module):
40
+ monkeypatch.delenv("QUANTDINGER_MCP_TRANSPORT", raising=False)
41
+ assert fresh_module._resolve_transport() == "stdio"
42
+
43
+
44
+ @pytest.mark.parametrize(
45
+ "raw,expected",
46
+ [
47
+ ("stdio", "stdio"),
48
+ ("STDIO", "stdio"),
49
+ ("sse", "sse"),
50
+ ("streamable-http", "streamable-http"),
51
+ ("http", "streamable-http"),
52
+ ("streaming-http", "streamable-http"),
53
+ ("STREAMABLE_HTTP", "streamable-http"),
54
+ ],
55
+ )
56
+ def test_transport_aliases_resolve(monkeypatch, fresh_module, raw, expected):
57
+ monkeypatch.setenv("QUANTDINGER_MCP_TRANSPORT", raw)
58
+ assert fresh_module._resolve_transport() == expected
59
+
60
+
61
+ def test_transport_unknown_exits(monkeypatch, fresh_module):
62
+ monkeypatch.setenv("QUANTDINGER_MCP_TRANSPORT", "bogus-transport")
63
+ with pytest.raises(SystemExit):
64
+ fresh_module._resolve_transport()
65
+
66
+
67
+ def test_apply_http_settings_without_error(monkeypatch, fresh_module):
68
+ """The shim must tolerate missing/odd settings shapes — never crash."""
69
+ monkeypatch.setenv("QUANTDINGER_MCP_HOST", "0.0.0.0")
70
+ monkeypatch.setenv("QUANTDINGER_MCP_PORT", "7777")
71
+ fake_settings = SimpleNamespace(host="127.0.0.1", port=8000)
72
+ monkeypatch.setattr(fresh_module, "mcp", SimpleNamespace(settings=fake_settings))
73
+ fresh_module._apply_http_settings_from_env()
74
+ assert fake_settings.host == "0.0.0.0"
75
+ assert fake_settings.port == 7777