tickwire-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.
Files changed (29) hide show
  1. tickwire_mcp-0.1.0/LICENSE +21 -0
  2. tickwire_mcp-0.1.0/PKG-INFO +149 -0
  3. tickwire_mcp-0.1.0/README.md +117 -0
  4. tickwire_mcp-0.1.0/pyproject.toml +52 -0
  5. tickwire_mcp-0.1.0/setup.cfg +4 -0
  6. tickwire_mcp-0.1.0/tests/test_bug067_tool_errors.py +91 -0
  7. tickwire_mcp-0.1.0/tests/test_bug068_069_guards.py +198 -0
  8. tickwire_mcp-0.1.0/tests/test_docs_search.py +109 -0
  9. tickwire_mcp-0.1.0/tests/test_example_guard.py +117 -0
  10. tickwire_mcp-0.1.0/tests/test_health.py +39 -0
  11. tickwire_mcp-0.1.0/tests/test_mcp_oauth.py +222 -0
  12. tickwire_mcp-0.1.0/tests/test_mcp_tools.py +451 -0
  13. tickwire_mcp-0.1.0/tests/test_packaging.py +73 -0
  14. tickwire_mcp-0.1.0/tests/test_public_address.py +120 -0
  15. tickwire_mcp-0.1.0/tests/test_stdio.py +67 -0
  16. tickwire_mcp-0.1.0/tickwire_mcp/__init__.py +16 -0
  17. tickwire_mcp-0.1.0/tickwire_mcp/__main__.py +287 -0
  18. tickwire_mcp-0.1.0/tickwire_mcp/api.py +73 -0
  19. tickwire_mcp-0.1.0/tickwire_mcp/docs_search.py +119 -0
  20. tickwire_mcp-0.1.0/tickwire_mcp/guards.py +191 -0
  21. tickwire_mcp-0.1.0/tickwire_mcp/idempotency.py +78 -0
  22. tickwire_mcp-0.1.0/tickwire_mcp/oauth.py +229 -0
  23. tickwire_mcp-0.1.0/tickwire_mcp/server.py +763 -0
  24. tickwire_mcp-0.1.0/tickwire_mcp.egg-info/PKG-INFO +149 -0
  25. tickwire_mcp-0.1.0/tickwire_mcp.egg-info/SOURCES.txt +27 -0
  26. tickwire_mcp-0.1.0/tickwire_mcp.egg-info/dependency_links.txt +1 -0
  27. tickwire_mcp-0.1.0/tickwire_mcp.egg-info/entry_points.txt +2 -0
  28. tickwire_mcp-0.1.0/tickwire_mcp.egg-info/requires.txt +10 -0
  29. tickwire_mcp-0.1.0/tickwire_mcp.egg-info/top_level.txt +1 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Tickwire
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,149 @@
1
+ Metadata-Version: 2.4
2
+ Name: tickwire-mcp
3
+ Version: 0.1.0
4
+ Summary: Tickwire MCP server: the safe execution layer for AI trading agents on MT4/MT5 (scoped agent keys, kill switches, pre-trade hooks, idempotent orders, truthful outcomes).
5
+ Author-email: Tickwire <hello@tickwire.io>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://tickwire.io/
8
+ Project-URL: Documentation, https://tickwire.io/ai-agents/
9
+ Project-URL: Changelog, https://tickwire.io/docs/changelog/
10
+ Keywords: mcp,model-context-protocol,metatrader,mt4,mt5,trading,ai-agents
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3 :: Only
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Topic :: Office/Business :: Financial :: Investment
20
+ Requires-Python: >=3.11
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ Requires-Dist: mcp==2.2.0
24
+ Requires-Dist: httpx<1,>=0.27
25
+ Requires-Dist: pydantic<3,>=2.6
26
+ Requires-Dist: uvicorn<1,>=0.27
27
+ Provides-Extra: dev
28
+ Requires-Dist: pytest>=8.0; extra == "dev"
29
+ Provides-Extra: examples
30
+ Requires-Dist: fastapi>=0.110; extra == "examples"
31
+ Dynamic: license-file
32
+
33
+ # tickwire-mcp
34
+
35
+ The Tickwire MCP server: MT4/MT5 trading tools for AI agents (Claude, Cursor,
36
+ ChatGPT through the API, the OpenAI Agents SDK, or your own), with the safety
37
+ built in. An agent uses its own **agent key** (`twag_…`), scoped to accounts
38
+ and optionally read-only. Every order goes through the owner's kill switches
39
+ and pre-trade hook, is idempotent, is audited with a required reason, and
40
+ comes back with a truthful outcome (`applied`, `no_change`, `rejected`,
41
+ `held` or `unknown`).
42
+
43
+ It is a thin client of the Tickwire agent API and never talks to terminals
44
+ directly. Full guide: [tickwire.io/ai-agents](https://tickwire.io/ai-agents/).
45
+
46
+ ## Install
47
+
48
+ **Not published yet.** The commands below won't find the package. Install from source, from the
49
+ repository root:
50
+
51
+ ```
52
+ pip install ./mcp # puts `tickwire-mcp` on PATH
53
+ ```
54
+
55
+ > **State on 30 Oct 2026:** still not published. To publish `tickwire-mcp`,
56
+ > `ops/local/release.sh` needs a PyPI token (Keychain item
57
+ > `tickwire-pypi-token`, or `~/.pypirc`). It is not on the Mac yet. The npm
58
+ > token for the TypeScript packages (`tickwire-npm-token`) is missing too. So
59
+ > the release cannot run until the owner adds them.
60
+
61
+ Once it is published:
62
+
63
+ ```
64
+ uvx tickwire-mcp --help # run without installing
65
+ pipx run tickwire-mcp --help
66
+ pip install tickwire-mcp # puts `tickwire-mcp` on PATH
67
+ ```
68
+
69
+ Python 3.11 or newer. MIT licensed.
70
+
71
+ ## Quick start: Claude Code
72
+
73
+ 1. The account owner creates an agent key (shown once) in the dashboard, or
74
+ with the Python SDK and their API key:
75
+ `Tickwire("https://api.tickwire.io", "YOUR_API_KEY").create_agent_key("my-claude", [account_id])`
76
+ (`POST /v1/agent-keys`). Start with `read_only=True` if the agent should
77
+ only look.
78
+ 2. Add the server:
79
+
80
+ ```bash
81
+ claude mcp add tickwire \
82
+ --env TICKWIRE_AGENT_KEY=twag_... \
83
+ --env TICKWIRE_API_URL=https://api.tickwire.io \
84
+ -- uvx tickwire-mcp stdio
85
+ ```
86
+
87
+ 3. Ask: *"List my Tickwire accounts, check the health of the first one, then
88
+ buy 0.01 lots of EURUSD. Reason: quickstart test."*
89
+
90
+ Sandbox and live accounts use the same API URL; the key decides which
91
+ accounts the agent sees. `--sandbox` (or `TICKWIRE_SANDBOX=1`) switches to
92
+ `TICKWIRE_SANDBOX_URL` instead.
93
+
94
+ **Claude Desktop / Cursor** (`claude_desktop_config.json`, `.cursor/mcp.json`):
95
+
96
+ ```json
97
+ {
98
+ "mcpServers": {
99
+ "tickwire": {
100
+ "command": "uvx",
101
+ "args": ["tickwire-mcp", "stdio"],
102
+ "env": {
103
+ "TICKWIRE_AGENT_KEY": "twag_...",
104
+ "TICKWIRE_API_URL": "https://api.tickwire.io"
105
+ }
106
+ }
107
+ }
108
+ }
109
+ ```
110
+
111
+ ## Configuration
112
+
113
+ | Variable | Meaning |
114
+ |---|---|
115
+ | `TICKWIRE_AGENT_KEY` | stdio: the agent key (`twag_…`). Hosted mode reads it per request from `Authorization: Bearer twag_…` |
116
+ | `TICKWIRE_API_URL` | the Tickwire API base URL |
117
+ | `TICKWIRE_SANDBOX=1` or `--sandbox` | use the sandbox instead |
118
+ | `TICKWIRE_SANDBOX_URL` | the sandbox API base URL; required with `--sandbox`. No sandbox host is built in, and it never falls back to live |
119
+ | `TICKWIRE_MCP_IDEMPOTENCY_WINDOW_S` | window for derived idempotency keys (default 60) |
120
+ | `TICKWIRE_MCP_ALLOWED_HOSTS` | hosted mode: accepted `Host` values (DNS-rebinding protection) |
121
+ | `TICKWIRE_MCP_MAX_BODY_BYTES` | hosted mode: largest `/mcp` request body (default 262144, 256 KB); larger gets 413 `payload_too_large` |
122
+ | `TICKWIRE_MCP_KEY_CHECK_TIMEOUT_S` | hosted mode: timeout of the agent-key check before `tools/call` (default 1) |
123
+ | `TICKWIRE_MCP_KEY_CHECK_TTL_S` | hosted mode: how long a valid key's check is cached (default 60) |
124
+
125
+ Hosted mode: `initialize` and `tools/list` need only a well-formed `twag_…`
126
+ key, on purpose, so MCP directories can list the tools with a placeholder.
127
+ `tools/call` checks the key first (`GET /v1/agent/key-check`) and answers 401
128
+ `invalid_agent_key` for a dead key, before any tool runs.
129
+
130
+ ## Modes
131
+
132
+ - `tickwire-mcp stdio` (default): one agent, local.
133
+ - `tickwire-mcp http --host 0.0.0.0 --port 8765`: streamable HTTP at `/mcp`
134
+ for many agents; each sends its own key. Put TLS in front.
135
+
136
+ ## Tools
137
+
138
+ `list_accounts`, `get_agent_permissions`, `get_portfolio`, `get_all_positions`, `get_account_health`,
139
+ `get_account_info`, `get_account_snapshot`, `get_positions`, `get_orders`, `get_quote`, `get_quotes`,
140
+ `search_symbols`, `get_symbol_spec`, `get_candles`, `get_history`, `get_history_stats`,
141
+ `place_order`, `modify_position`, `close_position`, `modify_order`, `cancel_order`, `get_trade_status`,
142
+ `get_audit_log`, and the read-only `search_tickwire_docs` (searches the public
143
+ docs at `TICKWIRE_DOCS_URL`/llms-full.txt; no account access). Every trading tool requires `reason` and accepts
144
+ `client_request_id` (the idempotency key); without one, a repeat within a
145
+ minute is recognised and not sent twice. Text from brokers, terminals and
146
+ hooks comes back wrapped as `{"untrusted_text": …}` so the model does not
147
+ follow instructions found in it.
148
+
149
+ Demo accounts only while you evaluate.
@@ -0,0 +1,117 @@
1
+ # tickwire-mcp
2
+
3
+ The Tickwire MCP server: MT4/MT5 trading tools for AI agents (Claude, Cursor,
4
+ ChatGPT through the API, the OpenAI Agents SDK, or your own), with the safety
5
+ built in. An agent uses its own **agent key** (`twag_…`), scoped to accounts
6
+ and optionally read-only. Every order goes through the owner's kill switches
7
+ and pre-trade hook, is idempotent, is audited with a required reason, and
8
+ comes back with a truthful outcome (`applied`, `no_change`, `rejected`,
9
+ `held` or `unknown`).
10
+
11
+ It is a thin client of the Tickwire agent API and never talks to terminals
12
+ directly. Full guide: [tickwire.io/ai-agents](https://tickwire.io/ai-agents/).
13
+
14
+ ## Install
15
+
16
+ **Not published yet.** The commands below won't find the package. Install from source, from the
17
+ repository root:
18
+
19
+ ```
20
+ pip install ./mcp # puts `tickwire-mcp` on PATH
21
+ ```
22
+
23
+ > **State on 30 Oct 2026:** still not published. To publish `tickwire-mcp`,
24
+ > `ops/local/release.sh` needs a PyPI token (Keychain item
25
+ > `tickwire-pypi-token`, or `~/.pypirc`). It is not on the Mac yet. The npm
26
+ > token for the TypeScript packages (`tickwire-npm-token`) is missing too. So
27
+ > the release cannot run until the owner adds them.
28
+
29
+ Once it is published:
30
+
31
+ ```
32
+ uvx tickwire-mcp --help # run without installing
33
+ pipx run tickwire-mcp --help
34
+ pip install tickwire-mcp # puts `tickwire-mcp` on PATH
35
+ ```
36
+
37
+ Python 3.11 or newer. MIT licensed.
38
+
39
+ ## Quick start: Claude Code
40
+
41
+ 1. The account owner creates an agent key (shown once) in the dashboard, or
42
+ with the Python SDK and their API key:
43
+ `Tickwire("https://api.tickwire.io", "YOUR_API_KEY").create_agent_key("my-claude", [account_id])`
44
+ (`POST /v1/agent-keys`). Start with `read_only=True` if the agent should
45
+ only look.
46
+ 2. Add the server:
47
+
48
+ ```bash
49
+ claude mcp add tickwire \
50
+ --env TICKWIRE_AGENT_KEY=twag_... \
51
+ --env TICKWIRE_API_URL=https://api.tickwire.io \
52
+ -- uvx tickwire-mcp stdio
53
+ ```
54
+
55
+ 3. Ask: *"List my Tickwire accounts, check the health of the first one, then
56
+ buy 0.01 lots of EURUSD. Reason: quickstart test."*
57
+
58
+ Sandbox and live accounts use the same API URL; the key decides which
59
+ accounts the agent sees. `--sandbox` (or `TICKWIRE_SANDBOX=1`) switches to
60
+ `TICKWIRE_SANDBOX_URL` instead.
61
+
62
+ **Claude Desktop / Cursor** (`claude_desktop_config.json`, `.cursor/mcp.json`):
63
+
64
+ ```json
65
+ {
66
+ "mcpServers": {
67
+ "tickwire": {
68
+ "command": "uvx",
69
+ "args": ["tickwire-mcp", "stdio"],
70
+ "env": {
71
+ "TICKWIRE_AGENT_KEY": "twag_...",
72
+ "TICKWIRE_API_URL": "https://api.tickwire.io"
73
+ }
74
+ }
75
+ }
76
+ }
77
+ ```
78
+
79
+ ## Configuration
80
+
81
+ | Variable | Meaning |
82
+ |---|---|
83
+ | `TICKWIRE_AGENT_KEY` | stdio: the agent key (`twag_…`). Hosted mode reads it per request from `Authorization: Bearer twag_…` |
84
+ | `TICKWIRE_API_URL` | the Tickwire API base URL |
85
+ | `TICKWIRE_SANDBOX=1` or `--sandbox` | use the sandbox instead |
86
+ | `TICKWIRE_SANDBOX_URL` | the sandbox API base URL; required with `--sandbox`. No sandbox host is built in, and it never falls back to live |
87
+ | `TICKWIRE_MCP_IDEMPOTENCY_WINDOW_S` | window for derived idempotency keys (default 60) |
88
+ | `TICKWIRE_MCP_ALLOWED_HOSTS` | hosted mode: accepted `Host` values (DNS-rebinding protection) |
89
+ | `TICKWIRE_MCP_MAX_BODY_BYTES` | hosted mode: largest `/mcp` request body (default 262144, 256 KB); larger gets 413 `payload_too_large` |
90
+ | `TICKWIRE_MCP_KEY_CHECK_TIMEOUT_S` | hosted mode: timeout of the agent-key check before `tools/call` (default 1) |
91
+ | `TICKWIRE_MCP_KEY_CHECK_TTL_S` | hosted mode: how long a valid key's check is cached (default 60) |
92
+
93
+ Hosted mode: `initialize` and `tools/list` need only a well-formed `twag_…`
94
+ key, on purpose, so MCP directories can list the tools with a placeholder.
95
+ `tools/call` checks the key first (`GET /v1/agent/key-check`) and answers 401
96
+ `invalid_agent_key` for a dead key, before any tool runs.
97
+
98
+ ## Modes
99
+
100
+ - `tickwire-mcp stdio` (default): one agent, local.
101
+ - `tickwire-mcp http --host 0.0.0.0 --port 8765`: streamable HTTP at `/mcp`
102
+ for many agents; each sends its own key. Put TLS in front.
103
+
104
+ ## Tools
105
+
106
+ `list_accounts`, `get_agent_permissions`, `get_portfolio`, `get_all_positions`, `get_account_health`,
107
+ `get_account_info`, `get_account_snapshot`, `get_positions`, `get_orders`, `get_quote`, `get_quotes`,
108
+ `search_symbols`, `get_symbol_spec`, `get_candles`, `get_history`, `get_history_stats`,
109
+ `place_order`, `modify_position`, `close_position`, `modify_order`, `cancel_order`, `get_trade_status`,
110
+ `get_audit_log`, and the read-only `search_tickwire_docs` (searches the public
111
+ docs at `TICKWIRE_DOCS_URL`/llms-full.txt; no account access). Every trading tool requires `reason` and accepts
112
+ `client_request_id` (the idempotency key); without one, a repeat within a
113
+ minute is recognised and not sent twice. Text from brokers, terminals and
114
+ hooks comes back wrapped as `{"untrusted_text": …}` so the model does not
115
+ follow instructions found in it.
116
+
117
+ Demo accounts only while you evaluate.
@@ -0,0 +1,52 @@
1
+ [project]
2
+ name = "tickwire-mcp"
3
+ version = "0.1.0"
4
+ description = "Tickwire MCP server: the safe execution layer for AI trading agents on MT4/MT5 (scoped agent keys, kill switches, pre-trade hooks, idempotent orders, truthful outcomes)."
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ requires-python = ">=3.11"
9
+ authors = [{ name = "Tickwire", email = "hello@tickwire.io" }]
10
+ keywords = ["mcp", "model-context-protocol", "metatrader", "mt4", "mt5", "trading", "ai-agents"]
11
+ classifiers = [
12
+ "Development Status :: 3 - Alpha",
13
+ "Intended Audience :: Developers",
14
+ "Operating System :: OS Independent",
15
+ "Programming Language :: Python :: 3",
16
+ "Programming Language :: Python :: 3 :: Only",
17
+ "Programming Language :: Python :: 3.11",
18
+ "Programming Language :: Python :: 3.12",
19
+ "Programming Language :: Python :: 3.13",
20
+ "Topic :: Office/Business :: Financial :: Investment",
21
+ ]
22
+ dependencies = [
23
+ # The official Model Context Protocol Python SDK (stdio + streamable HTTP).
24
+ "mcp==2.2.0",
25
+ "httpx>=0.27,<1",
26
+ "pydantic>=2.6,<3",
27
+ "uvicorn>=0.27,<1",
28
+ ]
29
+
30
+ [project.optional-dependencies]
31
+ dev = ["pytest>=8.0"]
32
+ # The example guard service (examples/example_guard.py).
33
+ examples = ["fastapi>=0.110"]
34
+
35
+ [project.scripts]
36
+ tickwire-mcp = "tickwire_mcp.__main__:main"
37
+
38
+ [project.urls]
39
+ Homepage = "https://tickwire.io/"
40
+ Documentation = "https://tickwire.io/ai-agents/"
41
+ Changelog = "https://tickwire.io/docs/changelog/"
42
+
43
+ [build-system]
44
+ requires = ["setuptools>=77"]
45
+ build-backend = "setuptools.build_meta"
46
+
47
+ [tool.setuptools.packages.find]
48
+ where = ["."]
49
+ include = ["tickwire_mcp*"]
50
+
51
+ [tool.pytest.ini_options]
52
+ testpaths = ["tests"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,91 @@
1
+ """BUG-067: a read tool whose API call failed is an MCP tool error
2
+ (``isError: true``) with the same error code the REST API gives."""
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+
7
+ import httpx
8
+ import pytest
9
+ from fastapi.testclient import TestClient
10
+ from mcp import Client
11
+
12
+ from stack import API, Stack, payload
13
+ from tickwire_mcp.api import TickwireApi
14
+ from tickwire_mcp.server import build_server
15
+
16
+ DATA_TOOLS = [
17
+ ("get_account_info", "account-information", {}),
18
+ ("get_account_snapshot", "snapshot", {}),
19
+ ("get_positions", "positions", {}),
20
+ ("get_orders", "orders", {}),
21
+ ("get_quote", "symbols/EURUSD/current-price", {"symbol": "EURUSD"}),
22
+ ("get_symbol_spec", "symbols/EURUSD/specification", {"symbol": "EURUSD"}),
23
+ ("get_candles", "symbols/EURUSD/candles", {"symbol": "EURUSD"}),
24
+ ("get_history", "history-deals", {}),
25
+ ]
26
+
27
+
28
+ async def _call(server, name: str, args: dict):
29
+ async with Client(server) as c:
30
+ return await c.call_tool(name, args)
31
+
32
+
33
+ @pytest.mark.parametrize("platform", ["mt5", "mt4"])
34
+ def test_unreachable_account_is_a_tool_error_with_the_rest_code(platform):
35
+ s = Stack()
36
+ acct, _ = s.add_account(platform)
37
+ key = s.agent_key([acct.id])
38
+ s.transport.apps.pop("bridge-1") # the terminal does not answer
39
+ server = s.server(key)
40
+ for tool, path, extra in DATA_TOOLS:
41
+ rest = TestClient(s.app).get(f"/v1/agent/accounts/{acct.id}/{path}",
42
+ headers={"X-Tickwire-Agent-Key": key})
43
+ result = asyncio.run(_call(server, tool, {"account_id": acct.id, **extra}))
44
+ out = payload(result)
45
+ assert result.is_error is True, (tool, out)
46
+ assert rest.status_code == 503, (tool, rest.text)
47
+ assert out["error"] == rest.json()["error"] == "account_unreachable", (tool, out)
48
+ assert out["http_status"] == 503
49
+ assert result.structured_content["error"] == "account_unreachable"
50
+
51
+
52
+ def test_every_failed_read_is_a_tool_error_and_success_is_not():
53
+ def handler(request):
54
+ if request.url.path.endswith("/positions"):
55
+ return httpx.Response(200, json={"data": []})
56
+ return httpx.Response(503, json={"error": "account_unreachable", "message": "down"})
57
+
58
+ server = build_server(lambda ctx: TickwireApi(API, "twag_x",
59
+ transport=httpx.MockTransport(handler)))
60
+ for tool, _, extra in DATA_TOOLS:
61
+ if tool == "get_positions":
62
+ continue
63
+ r = asyncio.run(_call(server, tool, {"account_id": "a1", **extra}))
64
+ assert r.is_error is True and payload(r)["error"] == "account_unreachable", tool
65
+ ok = asyncio.run(_call(server, "get_positions", {"account_id": "a1"}))
66
+ assert ok.is_error is False and "error" not in payload(ok)
67
+
68
+
69
+ def test_no_answer_is_a_tool_error():
70
+ def handler(request):
71
+ raise httpx.ConnectError("refused", request=request)
72
+
73
+ server = build_server(lambda ctx: TickwireApi(API, "twag_x",
74
+ transport=httpx.MockTransport(handler)))
75
+ r = asyncio.run(_call(server, "get_positions", {"account_id": "a1"}))
76
+ out = payload(r)
77
+ assert r.is_error is True and out["error"] == "tickwire_unreachable" and out["http_status"] == 0
78
+
79
+
80
+ def test_trade_failures_keep_their_outcome_contract():
81
+ def handler(request):
82
+ return httpx.Response(503, json={"error": "account_unreachable", "outcome": "rejected",
83
+ "sent": False, "message": "nothing was sent"})
84
+
85
+ server = build_server(lambda ctx: TickwireApi(API, "twag_x",
86
+ transport=httpx.MockTransport(handler)))
87
+ r = asyncio.run(_call(server, "place_order", {"account_id": "a1", "side": "buy",
88
+ "symbol": "EURUSD", "volume": 0.1,
89
+ "reason": "t"}))
90
+ out = payload(r)
91
+ assert r.is_error is False and out["outcome"] == "rejected" and out["sent"] is False
@@ -0,0 +1,198 @@
1
+ """BUG-068: tools/call with an invalid agent key is a fast 401, before any
2
+ tool runs; tools/list stays open to a well-formed key (directories).
3
+ BUG-069: /mcp refuses bodies over 256 KB with 413."""
4
+ from __future__ import annotations
5
+
6
+ import asyncio
7
+ import json
8
+ import time
9
+
10
+ import httpx
11
+ import pytest
12
+ from starlette.testclient import TestClient
13
+
14
+ from stack import API, Stack
15
+ from tickwire_mcp.__main__ import http_app
16
+ from tickwire_mcp.guards import KEY_CHECK_PATH, KeyCheck
17
+
18
+ HDRS = {"Accept": "application/json, text/event-stream", "Content-Type": "application/json",
19
+ "MCP-Protocol-Version": "2025-06-18"}
20
+ BAD = "twag_" + "z" * 43
21
+
22
+
23
+ def rpc(tc, method: str, params: dict, key: str | None, rid: int = 1, header: str = "bearer"):
24
+ h = dict(HDRS)
25
+ if key and header == "bearer":
26
+ h["Authorization"] = f"Bearer {key}"
27
+ elif key and header == "bare":
28
+ h["Authorization"] = key
29
+ elif key:
30
+ h["X-Tickwire-Agent-Key"] = key
31
+ return tc.post("/mcp", headers=h, json={"jsonrpc": "2.0", "id": rid, "method": method,
32
+ "params": params})
33
+
34
+
35
+ @pytest.fixture
36
+ def s() -> Stack:
37
+ return Stack()
38
+
39
+
40
+ def _paths(s) -> list[str]:
41
+ return [r.url.path for r in s.transport.requests]
42
+
43
+
44
+ # --------------------------------------------------------------------------- #
45
+ # BUG-068
46
+ # --------------------------------------------------------------------------- #
47
+ @pytest.mark.parametrize("header", ["bearer", "bare", "x-header"])
48
+ def test_tools_call_with_an_invalid_key_is_a_fast_401(s, header):
49
+ acct, be = s.add_account()
50
+ app = http_app(transport=s.transport, base_url=API, allowed_hosts=["testserver"])
51
+ with TestClient(app) as tc:
52
+ t0 = time.monotonic()
53
+ r = rpc(tc, "tools/call", {"name": "place_order", "arguments": {
54
+ "account_id": acct.id, "side": "buy", "symbol": "EURUSD", "volume": 0.1,
55
+ "reason": "x"}}, BAD, header=header)
56
+ took = time.monotonic() - t0
57
+ assert r.status_code == 401, r.text
58
+ assert r.json()["error"] == "invalid_agent_key" and BAD not in r.text
59
+ assert r.headers["www-authenticate"].startswith("Bearer")
60
+ assert took < 1.0
61
+ assert _paths(s) == [KEY_CHECK_PATH] # nothing else was called
62
+ assert be.send_count == 0
63
+
64
+
65
+ def test_tools_list_stays_open_to_a_well_formed_key(s):
66
+ """Deliberate (BUG-058): directories list tools with a placeholder key."""
67
+ app = http_app(transport=s.transport, base_url=API, allowed_hosts=["testserver"])
68
+ with TestClient(app) as tc:
69
+ r = rpc(tc, "tools/list", {}, BAD)
70
+ assert r.status_code == 200 and r.json()["result"]["tools"]
71
+ assert rpc(tc, "tools/list", {}, None).status_code == 401
72
+ assert rpc(tc, "tools/list", {}, "not-an-agent-key").status_code == 401
73
+ assert _paths(s) == [] # no key check for discovery
74
+
75
+
76
+ def test_valid_key_is_checked_once_then_cached(s):
77
+ acct, _ = s.add_account()
78
+ key = s.agent_key([acct.id])
79
+ app = http_app(transport=s.transport, base_url=API, allowed_hosts=["testserver"])
80
+ with TestClient(app) as tc:
81
+ for rid in (1, 2, 3):
82
+ r = rpc(tc, "tools/call", {"name": "get_positions",
83
+ "arguments": {"account_id": acct.id}}, key, rid)
84
+ assert r.status_code == 200 and not r.json()["result"].get("isError"), r.text
85
+ assert _paths(s).count(KEY_CHECK_PATH) == 1
86
+
87
+
88
+ def test_revoked_key_gets_401(s):
89
+ acct, _ = s.add_account()
90
+ key = s.agent_key([acct.id])
91
+ kid = s.owner.get("/v1/agent-keys").json()
92
+ kid = (kid.get("data") or kid.get("keys") or kid.get("items") or kid)[0]["id"]
93
+ assert s.owner.delete(f"/v1/agent-keys/{kid}").status_code == 204
94
+ app = http_app(transport=s.transport, base_url=API, allowed_hosts=["testserver"])
95
+ with TestClient(app) as tc:
96
+ r = rpc(tc, "tools/call", {"name": "list_accounts", "arguments": {}}, key)
97
+ assert r.status_code == 401 and r.json()["error"] == "invalid_agent_key"
98
+
99
+
100
+ def test_batch_with_a_tools_call_is_checked(s):
101
+ app = http_app(transport=s.transport, base_url=API, allowed_hosts=["testserver"])
102
+ h = {**HDRS, "Authorization": f"Bearer {BAD}"}
103
+ with TestClient(app) as tc:
104
+ r = tc.post("/mcp", headers=h, json=[
105
+ {"jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {}},
106
+ {"jsonrpc": "2.0", "id": 2, "method": "tools/call",
107
+ "params": {"name": "list_accounts", "arguments": {}}}])
108
+ assert r.status_code == 401
109
+
110
+
111
+ def _guard(handler, **kw) -> KeyCheck:
112
+ async def inner(scope, receive, send):
113
+ await send({"type": "http.response.start", "status": 200, "headers": []})
114
+ await send({"type": "http.response.body", "body": b"ran"})
115
+ return KeyCheck(inner, base_url=API, key_of=lambda h: (h.get("authorization") or "")[7:],
116
+ transport=httpx.MockTransport(handler), **kw)
117
+
118
+
119
+ def _call_guard(guard) -> int:
120
+ tc = TestClient(guard) # no lifespan: the inner app is bare ASGI
121
+ return tc.post("/mcp", headers={"Authorization": "Bearer twag_abc"},
122
+ json={"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {}}).status_code
123
+
124
+
125
+ def test_check_fails_open_when_the_api_cannot_answer():
126
+ def down(request):
127
+ raise httpx.ConnectError("refused", request=request)
128
+ assert _call_guard(_guard(down)) == 200
129
+
130
+ def broken(request):
131
+ return httpx.Response(503, json={"error": "service_unavailable"})
132
+ assert _call_guard(_guard(broken)) == 200
133
+
134
+ def old_api(request):
135
+ return httpx.Response(404, json={"error": "not_found"})
136
+ assert _call_guard(_guard(old_api)) == 200
137
+
138
+
139
+ def test_slow_check_gives_up_within_the_timeout():
140
+ async def slow(request):
141
+ await asyncio.sleep(3)
142
+ return httpx.Response(401)
143
+
144
+ class Slow(httpx.AsyncBaseTransport):
145
+ async def handle_async_request(self, request):
146
+ return await slow(request)
147
+
148
+ async def inner(scope, receive, send):
149
+ await send({"type": "http.response.start", "status": 200, "headers": []})
150
+ await send({"type": "http.response.body", "body": b"ran"})
151
+ guard = KeyCheck(inner, base_url=API, key_of=lambda h: (h.get("authorization") or "")[7:],
152
+ transport=Slow(), timeout_s=0.2)
153
+ t0 = time.monotonic()
154
+ assert _call_guard(guard) == 200
155
+ assert time.monotonic() - t0 < 2.0
156
+
157
+
158
+ def test_invalid_answer_is_cached_for_a_while():
159
+ seen = []
160
+
161
+ def handler(request):
162
+ seen.append(request)
163
+ return httpx.Response(401, json={"error": "invalid_agent_key"})
164
+ now = [100.0]
165
+ guard = _guard(handler, clock=lambda: now[0], bad_ttl_s=30)
166
+ assert _call_guard(guard) == 401 and _call_guard(guard) == 401 and len(seen) == 1
167
+ now[0] += 31
168
+ assert _call_guard(guard) == 401 and len(seen) == 2
169
+ assert seen[0].headers["x-tickwire-agent-key"] == "twag_abc"
170
+
171
+
172
+ # --------------------------------------------------------------------------- #
173
+ # BUG-069
174
+ # --------------------------------------------------------------------------- #
175
+ def test_body_over_256_kb_is_413(s):
176
+ acct, _ = s.add_account()
177
+ key = s.agent_key([acct.id])
178
+ app = http_app(transport=s.transport, base_url=API, allowed_hosts=["testserver"])
179
+ big = {"jsonrpc": "2.0", "id": 1, "method": "tools/call",
180
+ "params": {"name": "get_positions", "arguments": {"account_id": "x" * (300 * 1024)}}}
181
+ with TestClient(app) as tc:
182
+ r = tc.post("/mcp", headers={**HDRS, "Authorization": f"Bearer {key}"},
183
+ content=json.dumps(big))
184
+ assert r.status_code == 413 and r.json()["error"] == "payload_too_large"
185
+
186
+ def chunks(): # no Content-Length: streamed
187
+ data = json.dumps(big).encode()
188
+ for i in range(0, len(data), 64 * 1024):
189
+ yield data[i:i + 64 * 1024]
190
+ r = tc.post("/mcp", headers={**HDRS, "Authorization": f"Bearer {key}"}, content=chunks())
191
+ assert r.status_code == 413 and r.json()["error"] == "payload_too_large"
192
+ # no credentials needed to be refused for size, and nothing is called
193
+ r = tc.post("/mcp", headers=HDRS, content=json.dumps(big))
194
+ assert r.status_code == 413
195
+ ok = rpc(tc, "tools/call", {"name": "get_positions",
196
+ "arguments": {"account_id": acct.id}}, key)
197
+ assert ok.status_code == 200
198
+ assert KEY_CHECK_PATH in _paths(s) and len(_paths(s)) == 3 # check, positions -> bridge