Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ jobs:
run: uv sync
- name: Compile
run: uv run python -m compileall -q pirate_ship_api_mcp
- name: Cookie scope tests
run: uv run python -m unittest discover -s tests
- name: MCP server starts and lists its tools
run: |
uv run python - <<'PY'
Expand Down
4 changes: 2 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ Do the steps yourself. Ask the user only for what needs their hands in Chrome.
On Windows the path is `.venv\Scripts\pirate-ship-mcp`. With uv: `uv venv && uv pip install -e .`.
3. Ask the user to do two things in Chrome. You cannot open `chrome://` pages for them.
- Open `chrome://inspect/#remote-debugging` and switch remote debugging on.
- Be signed in at https://ship.pirateship.com, with "Stay signed in" ticked.
- Sign in at https://ship.pirateship.com, with "Stay signed in" ticked, and leave the tab open.
4. Run `.venv/bin/pirate-ship-mcp connect`. Tell the user to click **Allow** when Chrome asks about the connection. Success prints `Signed in to Pirate Ship as <name> (<email>)`.
5. Check: `.venv/bin/pirate-ship-mcp status`, then `.venv/bin/pirate-ship-mcp call get_account_balance`.
6. Add the MCP server to the user's client. Use the absolute path of `.venv/bin/pirate-ship-mcp`:
Expand Down Expand Up @@ -74,4 +74,4 @@ Errors come as `<code>: <message>`. `auth_expired` means Pirate Ship signed the

A new tool is a new file in `pirate_ship_api_mcp/pirate_ship/tools/` with a `@tool(...)` declaration (name, access, input schema, `route`). The registry finds it, and the REST API, the MCP server and the CLI show it without other changes. A new GraphQL operation also needs its name and sha256 in `operations.py`.

There is no test suite. After a change, run `.venv/bin/pirate-ship-mcp tools` and one read tool against the user's account.
Run `.venv/bin/python -m unittest discover -s tests` for the offline cookie scope tests. After a change, run `.venv/bin/pirate-ship-mcp tools` and one read tool against the user's account.
10 changes: 5 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ AI agent (MCP) / script (REST, Python) ──▶ pirate-ship-mcp on your compute
```

1. You sign in to Pirate Ship in your own Chrome, the way you always do.
2. `pirate-ship-mcp connect` attaches to that Chrome through the Chrome DevTools Protocol, reads the pirateship.com cookies and Chrome's time zone, and saves them to `~/.config/pirate-ship-api-mcp/session.json`, readable by your user only. It never sees or stores your password.
2. `pirate-ship-mcp connect` attaches to the open Pirate Ship tab through the Chrome DevTools Protocol. Chrome returns only cookies that apply to the Pirate Ship API URL; the CLI saves only the declared Pirate Ship session cookie and the browser's time zone to `~/.config/pirate-ship-api-mcp/session.json`, readable by your user only. It never sees or stores your password.
3. Every tool call is one of the GraphQL operations Pirate Ship's own web app sends to `ship.pirateship.com/api/graphql`, with those cookies, sent with [curl_cffi](https://github.com/lexiforest/curl_cffi), which copies Chrome's TLS fingerprint. No headless browser runs.

Pirate Ship's web app sends each operation as a persisted query: its name and the sha256 of the query text. The tools may send only the operations listed in [`operations.py`](https://github.com/cotletdev/pirate-ship-api-mcp-server/blob/main/pirate_ship_api_mcp/pirate_ship/operations.py), and account, password, payment method and identity operations are not on that list. When Pirate Ship changes one of the listed queries, the tool answers "Pirate Ship changed its app" until we record the new hash.
Expand Down Expand Up @@ -165,7 +165,7 @@ To update: `uv tool upgrade pirate-ship-api-mcp` (or `pip install -U pirate-ship
### Option A: your everyday Chrome (recommended)

1. Open `chrome://inspect/#remote-debugging` in Chrome and switch **remote debugging** on. Chrome then accepts DevTools connections from programs on this computer, and asks you before each one.
2. Make sure you are signed in at [ship.pirateship.com](https://ship.pirateship.com).
2. Open [ship.pirateship.com](https://ship.pirateship.com), sign in, and leave the tab open.
3. Run:

```bash
Expand All @@ -175,7 +175,7 @@ To update: `uv tool upgrade pirate-ship-api-mcp` (or `pip install -U pirate-ship
4. Chrome asks whether to allow the connection. Click **Allow**.

```text
Saved 32 Pirate Ship cookies to /Users/you/.config/pirate-ship-api-mcp/session.json
Saved 1 Pirate Ship cookies to /Users/you/.config/pirate-ship-api-mcp/session.json
Signed in to Pirate Ship as Linda Morales (linda@example.com)
```

Expand Down Expand Up @@ -485,10 +485,10 @@ In tool descriptions "buy it with buy_label" means: buy the draft in Pirate Ship

## Security and your Pirate Ship account

- **Your password never reaches this code.** Only cookies are read, and only those of pirateship.com.
- **Your password never reaches this code.** Chrome scopes the lookup to the Pirate Ship API URL, and the CLI retains only the session cookie, not unrelated Pirate Ship cookies.
- **The session file is yours.** `session.json` is created with mode 0600. Anyone who has it can act as you on Pirate Ship, so keep it out of git and shared folders.
- **Local by default.** `serve` binds to `127.0.0.1` and refuses another address without `PIRATE_SHIP_MCP_TOKEN`.
- **pirateship.com only.** Requests and redirects outside pirateship.com are refused.
- **HTTPS on pirateship.com only.** Cross-domain redirects and redirects that downgrade to HTTP are refused.
- **No tool moves money.** None buys a label, requests a refund, books a paid pickup or touches your payment methods.
- **Read-only mode.** `--read-only` or `PIRATE_SHIP_MCP_READ_ONLY=1` exposes the 29 read tools only.
- **Some changes reach your recipients.** Tracking email settings and templates change the emails your customers get. MCP clients ask before those tools run; a script does not.
Expand Down
2 changes: 2 additions & 0 deletions pirate_ship_api_mcp/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
SESSION_COOKIES = ("pirate_id_f0fecf84",)
COOKIE_DOMAIN = "ship.pirateship.com"
LOGIN_URL = "https://ship.pirateship.com/"
# Ask Chrome only for cookies that would apply to the authenticated API request.
SESSION_COOKIE_URL = f"{LOGIN_URL}api/graphql"
# A final URL with one of these means the app signed the session out.
LOGGED_OUT_MARKERS = ("/login",)
# Pirate Ship answers every call on one GraphQL path, so no account path to refuse here: the allowlist of
Expand Down
11 changes: 6 additions & 5 deletions pirate_ship_api_mcp/core/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,9 @@ def json(self) -> Any:


def allowed_host(url: str) -> bool:
host = (urlsplit(url).hostname or "").lower()
return any(host == domain or host.endswith(f".{domain}") for domain in DOMAINS)
parsed = urlsplit(url)
host = (parsed.hostname or "").lower()
return parsed.scheme == "https" and any(host == domain or host.endswith(f".{domain}") for domain in DOMAINS)


def impersonate_target(chrome_major: int | None) -> str:
Expand Down Expand Up @@ -110,7 +111,7 @@ def _client(self) -> AsyncSession:
self._http = AsyncSession(impersonate=target, proxy=self.session.proxy or None, headers=headers) # pyright: ignore[reportArgumentType] - target is a BrowserType value
for cookie in self.session.cookies:
self._http.cookies.set(
cookie["name"], cookie["value"], domain=cookie["domain"], path=cookie.get("path", "/")
cookie["name"], cookie["value"], domain=cookie["domain"], path=cookie.get("path", "/"), secure=True
)
return self._http

Expand All @@ -120,7 +121,7 @@ async def call(self, method: str, url: str, **kwargs: Any) -> HttpResponse:
Writes to your account settings in the app are refused before they leave (account_guard).
"""
if not allowed_host(url):
raise ToolError(f"Request outside {app.DOMAINS[0]}.", ErrorCode.INTERNAL_ERROR)
raise ToolError(f"Request must use HTTPS on {app.DOMAINS[0]}.", ErrorCode.INTERNAL_ERROR)
check_account_write(method, url)
client = self._client()
method = method.upper()
Expand Down Expand Up @@ -149,7 +150,7 @@ async def call(self, method: str, url: str, **kwargs: Any) -> HttpResponse:
break
url = urljoin(str(raw.url), location)
if not allowed_host(url):
raise ToolError(f"{app.NAME} redirected outside {app.DOMAINS[0]}.", ErrorCode.TARGET_ERROR)
raise ToolError(f"{app.NAME} redirected outside HTTPS on {app.DOMAINS[0]}.", ErrorCode.TARGET_ERROR)
params = None
if raw.status_code == 303 or (raw.status_code in (301, 302) and method == "POST"):
method, json, data = "GET", None, None
Expand Down
79 changes: 55 additions & 24 deletions pirate_ship_api_mcp/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,25 @@
SESSION_COOKIE = app.SESSION_COOKIES[0]


def _session_cookies(cookies: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""Keep only declared session cookie names on the app host or its official parent domain."""
allowed_domains = {app.COOKIE_DOMAIN, *app.DOMAINS}
selected = []
for cookie in cookies:
if not isinstance(cookie, dict):
continue
name, value, domain = (cookie.get(key) for key in ("name", "value", "domain"))
if (
name in app.SESSION_COOKIES
and isinstance(value, str)
and value
and isinstance(domain, str)
and domain.lower().removeprefix(".") in allowed_domains
):
selected.append({"name": name, "value": value, "domain": domain, "path": cookie.get("path") or "/"})
return selected


def home() -> Path:
"""Where the session is kept: $<ENV>_MCP_HOME, or ~/.config/<slug>-api-mcp."""
return Path(os.environ.get(f"{app.ENV}_MCP_HOME") or Path.home() / ".config" / f"{app.SLUG}-api-mcp")
Expand Down Expand Up @@ -63,6 +82,7 @@ def load() -> Session:
if path.exists():
data = json.loads(path.read_text(encoding="utf-8"))
session = Session(**{k: v for k, v in data.items() if k in Session.__dataclass_fields__})
session.cookies = _session_cookies(session.cookies)
if token := os.environ.get(f"{app.ENV}_AUTH_TOKEN", "").strip():
session.cookies = [c for c in session.cookies if c["name"] != SESSION_COOKIE]
session.cookies.append({"name": SESSION_COOKIE, "value": token, "domain": app.COOKIE_DOMAIN, "path": "/"})
Expand All @@ -77,7 +97,7 @@ def save(session: Session) -> Path:
path.parent.mkdir(parents=True, exist_ok=True)
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, stat.S_IRUSR | stat.S_IWUSR)
with os.fdopen(fd, "w", encoding="utf-8") as fh:
json.dump(asdict(session), fh, indent=2)
json.dump({**asdict(session), "cookies": _session_cookies(session.cookies)}, fh, indent=2)
os.chmod(path, stat.S_IRUSR | stat.S_IWUSR)
return path

Expand Down Expand Up @@ -167,28 +187,30 @@ def system_timezone() -> str:
return target.split("zoneinfo/", 1)[1] if "zoneinfo/" in target else "UTC"


def _chrome_timezone(client: _Cdp) -> str | None:
"""Chrome's own time zone, read in one of its open tabs. Nothing in the tab changes."""
def _chrome_timezone(client: _Cdp, session_id: str) -> str | None:
"""Chrome's own time zone, read in the already attached app tab."""
try:
pages = [t for t in client.send("Target.getTargets").get("targetInfos") or [] if t.get("type") == "page"]
if not pages:
return None
attached = client.send("Target.attachToTarget", {"targetId": pages[0]["targetId"], "flatten": True})
session_id = attached["sessionId"]
try:
result = client.send(
"Runtime.evaluate",
{"expression": "Intl.DateTimeFormat().resolvedOptions().timeZone", "returnByValue": True},
session_id,
)
finally:
client.send("Target.detachFromTarget", {"sessionId": session_id})
result = client.send(
"Runtime.evaluate",
{"expression": "Intl.DateTimeFormat().resolvedOptions().timeZone", "returnByValue": True},
session_id,
)
value = (result.get("result") or {}).get("value")
return value if isinstance(value, str) and value else None
except (ToolError, KeyError, TimeoutError):
return None


def _app_page(target: dict[str, Any]) -> bool:
if target.get("type") != "page":
return False
try:
url = urlsplit(target.get("url", ""))
return url.scheme == "https" and url.hostname == app.COOKIE_DOMAIN and url.port in (None, 443)
except ValueError:
return False


def from_chrome(cdp: str | None = None, profile_dir: str | None = None) -> Session:
"""Read the app's cookies of a running Chrome. Nothing is changed in the browser."""
url = _endpoint(cdp) if cdp else auto_endpoint(profile_dir)
Expand All @@ -202,19 +224,28 @@ def from_chrome(cdp: str | None = None, profile_dir: str | None = None) -> Sessi
) from exc
try:
version = client.send("Browser.getVersion")
cookies = client.send("Storage.getCookies").get("cookies") or []
timezone = _chrome_timezone(client)
pages = [target for target in client.send("Target.getTargets").get("targetInfos", []) if _app_page(target)]
if not pages:
raise ToolError(f"Open the signed-in {app.NAME} tab at {app.LOGIN_URL}, then retry.", ErrorCode.AUTH_REQUIRED)
if len({page.get("browserContextId") for page in pages}) > 1:
raise ToolError(
f"{app.NAME} tabs are open in multiple Chrome profiles. Leave it open only in the intended profile, then retry.",
ErrorCode.AUTH_REQUIRED,
)
attached = client.send("Target.attachToTarget", {"targetId": pages[0]["targetId"], "flatten": True})
session_id = attached["sessionId"]
try:
# The browser filters by URL before returning any cookie values.
cookies = client.send("Network.getCookies", {"urls": [app.SESSION_COOKIE_URL]}, session_id).get("cookies", [])
timezone = _chrome_timezone(client, session_id)
finally:
client.send("Target.detachFromTarget", {"sessionId": session_id})
finally:
client.close()
mine = [
{"name": c["name"], "value": c["value"], "domain": c["domain"], "path": c.get("path") or "/"}
for c in cookies
if any(c.get("domain", "").lstrip(".").endswith(domain) for domain in app.DOMAINS)
]
user_agent = version.get("userAgent")
match = re.search(r"Chrome/(\d+)", user_agent or "") or re.search(r"/(\d+)\.", version.get("product", ""))
session = Session(
cookies=mine,
cookies=_session_cookies(cookies),
user_agent=user_agent,
chrome_major=int(match.group(1)) if match else None,
source=cdp or "auto",
Expand Down
104 changes: 104 additions & 0 deletions tests/test_cookie_scope.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
"""Offline checks; the browser fixture never sees a real account or cookie."""

import json
import tempfile
import unittest
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, call, patch

from pirate_ship_api_mcp import app, session
from pirate_ship_api_mcp.core.context import ToolContext, allowed_host
from pirate_ship_api_mcp.core.errors import ErrorCode, ToolError


def cookie(domain=app.COOKIE_DOMAIN, name=session.SESSION_COOKIE):
return {"name": name, "value": "synthetic-cookie", "domain": domain, "path": "/"}


class SessionTests(unittest.TestCase):
def browser(self, targets):
client = MagicMock()
answers = {
"Browser.getVersion": {"userAgent": "Chrome/144.0.0.0"},
"Target.getTargets": {"targetInfos": targets},
"Target.attachToTarget": {"sessionId": "tab-session"},
"Network.getCookies": {"cookies": [cookie(app.COOKIE_DOMAIN, "analytics"), cookie("notpirateship.com"),
cookie(".pirateship.com")]},
"Runtime.evaluate": {"result": {"value": "America/Phoenix"}},
"Target.detachFromTarget": {},
}
client.send.side_effect = lambda method, *_: answers[method]
return client

def test_scoped_target_cookie_call(self):
client = self.browser([
{"type": "page", "url": "https://notpirateship.com/", "targetId": "lookalike"},
{"type": "page", "url": "https://ship.pirateship.com/ship", "targetId": "app"},
])
with patch.object(session, "_Cdp", return_value=client):
result = session.from_chrome("ws://127.0.0.1:1234/test")
self.assertTrue(result.signed_in)
self.assertEqual(result.cookies, [cookie(".pirateship.com")])
self.assertEqual(result.timezone, "America/Phoenix")
self.assertEqual(
client.send.call_args_list[:4],
[call("Browser.getVersion"), call("Target.getTargets"),
call("Target.attachToTarget", {"targetId": "app", "flatten": True}),
call("Network.getCookies", {"urls": ["https://ship.pirateship.com/api/graphql"]}, "tab-session")],
)
self.assertEqual(client.send.call_args_list[-1], call("Target.detachFromTarget", {"sessionId": "tab-session"}))
client.close.assert_called_once_with()

def test_never_reads_from_unrelated_or_ambiguous_pages(self):
for targets in (
[{"type": "page", "url": "http://ship.pirateship.com/", "targetId": "insecure"}],
[{"type": "page", "url": app.LOGIN_URL, "targetId": i, "browserContextId": i} for i in ("one", "two")],
):
client = self.browser(targets)
with patch.object(session, "_Cdp", return_value=client), self.assertRaises(ToolError) as raised:
session.from_chrome("ws://127.0.0.1:1234/test")
self.assertEqual(raised.exception.code, ErrorCode.AUTH_REQUIRED)
self.assertEqual(client.send.call_args_list, [call("Browser.getVersion"), call("Target.getTargets")])
client.close.assert_called_once_with()

def test_narrows_existing_caches_and_keeps_manual_login_supported(self):
with tempfile.TemporaryDirectory() as folder, patch.dict("os.environ", {}, clear=True):
path = Path(folder) / "session.json"
cookies = [cookie(), cookie(".notpirateship.com"), cookie(name="analytics")]
path.write_text(json.dumps({"cookies": cookies}))
with patch.object(session, "session_path", return_value=path):
self.assertEqual(session.load().cookies, [cookie()])
session.save(session.Session(cookies=cookies))
self.assertEqual(json.loads(path.read_text())["cookies"], [cookie()])
self.assertTrue(session.from_token("synthetic-manual-token").signed_in)


class HttpsTests(unittest.IsolatedAsyncioTestCase):
def test_host_boundary_and_https(self):
self.assertTrue(allowed_host(app.SESSION_COOKIE_URL))
self.assertFalse(allowed_host("http://ship.pirateship.com/api/graphql"))
self.assertFalse(allowed_host("https://notpirateship.com/api/graphql"))

async def test_never_follows_http_downgrade(self):
req = AsyncMock(return_value=SimpleNamespace(
headers={"location": "http://ship.pirateship.com/api/graphql"},
status_code=302,
url=app.SESSION_COOKIE_URL,
))
context = ToolContext(session.Session(cookies=[cookie()]), _http=SimpleNamespace(request=req))
with self.assertRaises(ToolError) as raised:
await context.call("GET", app.SESSION_COOKIE_URL)
self.assertEqual(raised.exception.code, ErrorCode.TARGET_ERROR)
req.assert_awaited_once()

async def test_cookie_jar_requires_https(self):
context = ToolContext(session.Session(cookies=[cookie()]))
try:
self.assertTrue(next(iter(context._client().cookies.jar)).secure)
finally:
await context.close()


if __name__ == "__main__":
unittest.main()