patentref-mcp 0.4.0__py3-none-any.whl

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,2 @@
1
+ """patentref-mcp: the PatentRef API as MCP tools."""
2
+ __version__ = "0.4.0"
@@ -0,0 +1,233 @@
1
+ """PatentRef MCP server: the public API as tools, over stdio (default) or streamable HTTP.
2
+
3
+ patentref-mcp stdio
4
+ patentref-mcp --http --port 8787 streamable HTTP at /mcp
5
+
6
+ Env: PATENTREF_API_KEY (the X-Api-Key value; never logged), PATENTREF_BASE (default https://patentref.io),
7
+ PATENTREF_TIMEOUT (seconds, default 30). The server is a thin client: every tool returns the API's own JSON
8
+ and states nothing of its own (PatentRef never-regress item 8).
9
+ """
10
+ import argparse
11
+ import json
12
+ import logging
13
+ import os
14
+ import sys
15
+ from typing import Any
16
+
17
+ import httpx
18
+ from mcp.server.fastmcp import FastMCP
19
+
20
+ BASE = os.environ.get("PATENTREF_BASE", "https://patentref.io").rstrip("/")
21
+ TIMEOUT = float(os.environ.get("PATENTREF_TIMEOUT", "30"))
22
+ USER_AGENT = "patentref-mcp/0.4.0"
23
+
24
+ INSTRUCTIONS = (
25
+ "PatentRef serves the USPTO PatentsView granted-patent corpus with the PatentSearch v1 grammar plus expiry facts. "
26
+ "check_patent_status gives record facts (status, basis, as-of date, data version) and never a legal conclusion; "
27
+ "quote its `plain` sentence rather than paraphrasing it. search_patents takes the v1 q/f/s grammar "
28
+ "(https://patentref.io/llms-full.txt). Every answer carries data_version and as_of; cite them. "
29
+ "get_claim_tree gives one patent's claims as a tree with every span located by offsets in the claim text as published; "
30
+ "quote the claim text at those offsets, and read its flags as notes on the text, never as a conclusion about the claims. "
31
+ "get_patent_brief gives one patent in a fixed order cut to fit max_tokens (identity, status, each independent claim's "
32
+ "elements with their offsets, one line per dependent claim, the claim term keys; truncated and omitted say what the budget "
33
+ "left out); quote its text fields as given and cite a claim or element by its page and anchor (page#anchor). "
34
+ "The rules tools (rep_required, fee_schedule, route_windows, pph_routes, ai_use_statement_required, grace_period, "
35
+ "rules_changelog, rules_index) answer rows of office rules, each with its official source URL and a verbatim quote, plus "
36
+ "rules_version and as_of; quote the row and its citation_url. They take an office, never an application number or a "
37
+ "priority date, and compute no date for an application."
38
+ )
39
+
40
+ mcp = FastMCP("patentref", instructions=INSTRUCTIONS, log_level="WARNING")
41
+ logging.getLogger("httpx").setLevel(logging.WARNING)
42
+
43
+
44
+ class ApiError(Exception):
45
+ pass
46
+
47
+
48
+ def _key():
49
+ return os.environ.get("PATENTREF_API_KEY", "").strip()
50
+
51
+
52
+ def _call(path: str, params: dict[str, Any] | None = None, keyed: bool = True) -> dict[str, Any]:
53
+ headers = {"Accept": "application/json", "User-Agent": USER_AGENT}
54
+ if keyed:
55
+ key = _key()
56
+ if not key:
57
+ raise ApiError("PATENTREF_API_KEY is not set; get a Free key at https://patentref.io/api/v1/meta/signup/")
58
+ headers["X-Api-Key"] = key
59
+ try:
60
+ r = httpx.get(BASE + path, params=params, headers=headers, timeout=TIMEOUT)
61
+ except httpx.HTTPError as e:
62
+ raise ApiError(f"request failed: {e.__class__.__name__}") from None
63
+ if r.status_code >= 400:
64
+ reason = r.headers.get("X-Status-Reason") or ""
65
+ code = r.headers.get("X-Status-Reason-Code") or ""
66
+ retry = r.headers.get("Retry-After")
67
+ text = f"HTTP {r.status_code}"
68
+ if code:
69
+ text += f" {code}"
70
+ if reason:
71
+ text += f": {reason}"
72
+ if retry:
73
+ text += f" (retry after {retry} s)"
74
+ if not code and not reason:
75
+ try:
76
+ text += ": " + json.dumps(r.json())[:300]
77
+ except ValueError:
78
+ pass
79
+ raise ApiError(text)
80
+ try:
81
+ return r.json()
82
+ except ValueError:
83
+ raise ApiError("the API answered with a non-JSON body") from None
84
+
85
+
86
+ @mcp.tool()
87
+ def check_patent_status(patent_id: str) -> dict[str, Any]:
88
+ """The one-call verdict for one US patent: status (active, expired_term, expired_fee_nonpayment, withdrawn,
89
+ unknown), basis entries, reinstatement_possible with its 37 CFR 1.378 basis, as_of, data_version, the versioned
90
+ permalink, a one-sentence `plain` record statement and next_steps. Record facts only."""
91
+ pid = patent_id.strip().upper()
92
+ pid = pid[2:] if pid.startswith("US") else pid
93
+ return _call(f"/api/v1/lapse/status/{pid}/")
94
+
95
+
96
+ @mcp.tool()
97
+ def search_patents(q: dict[str, Any], f: list[str] | None = None, s: list[dict[str, str]] | None = None,
98
+ size: int = 25, after: list[Any] | None = None) -> dict[str, Any]:
99
+ """Search granted US patents with the PatentSearch v1 grammar: q is one JSON object with one key
100
+ (for example {"patent_title": "laser"} or {"_and": [{"_gte": {"patent_date": "2015-01-01"}}, {"cpc_current.cpc_group_id": "H01S3/00"}]}),
101
+ f the fields to return (add "lapse" for the expiry group: expiry_status, expiry_date_estimated, expiry_basis,
102
+ reinstatement_possible, fee_status, lapse_date), s the sort (for example [{"patent_date": "desc"}]), size up to 1000,
103
+ after the cursor from the previous page's last sort values."""
104
+ params = {"q": json.dumps(q), "o": json.dumps({"size": max(1, min(int(size), 1000)), **({"after": after} if after else {})})}
105
+ if f:
106
+ params["f"] = json.dumps(f)
107
+ if s:
108
+ params["s"] = json.dumps(s)
109
+ return _call("/api/v1/patent/", params)
110
+
111
+
112
+ @mcp.tool()
113
+ def similar_patents(text: str, n: int = 20) -> dict[str, Any]:
114
+ """The n (1 to 20) US patents nearest to a title plus abstract by FTS5 bm25 over title and abstract, with
115
+ data_version and as_of. A record of what the corpus contained, not a search opinion."""
116
+ return _call("/api/v1/lapse/similar", {"text": text[:4000], "n": max(1, min(int(n), 20))})
117
+
118
+
119
+ @mcp.tool()
120
+ def get_claim_tree(patent_id: str) -> dict[str, Any]:
121
+ """The claims of one US patent as a tree, from the claim text the USPTO published: per claim its number, category,
122
+ dependency, preamble, transition, elements, term mentions with the earlier mention each "the"/"said" phrase was matched
123
+ to, claim references and flags; the relations between those parts; structure_version, data_version, text_data_version
124
+ and as_of. Every part carries start and end offsets into its claim's text (text[start:end] is the part). Flags describe
125
+ the text and the data only. GET /api/v1/structure/claims/<patent_id>/."""
126
+ pid = patent_id.strip().upper()
127
+ pid = pid[2:] if pid.startswith("US") else pid
128
+ return _call(f"/api/v1/structure/claims/{pid}/")
129
+
130
+
131
+ @mcp.tool()
132
+ def get_patent_brief(patent_id: str, max_tokens: int = 2000) -> dict[str, Any]:
133
+ """A brief of one US patent that fits max_tokens (300 to 32000, default 2000), in a fixed order: identity and dates,
134
+ the status record with its basis, each independent claim as its elements with start and end offsets into the claim
135
+ text, each dependent claim on one line, and the claim term keys; the first item that does not fit ends the brief,
136
+ and truncated and omitted say what was left out. tokens counts the answer by the stated proxy in tokenizer (UTF-8
137
+ bytes / 3, rounded up), never over max_tokens. Every claim and element carries anchor: page + "#" + anchor opens it
138
+ on the record page. Quotes are the claim text as published. GET /api/v1/structure/brief/<patent_id>/?max_tokens=."""
139
+ pid = patent_id.strip().upper()
140
+ pid = pid[2:] if pid.startswith("US") else pid
141
+ return _call(f"/api/v1/structure/brief/{pid}/", {"max_tokens": max(300, min(int(max_tokens), 32000))})
142
+
143
+
144
+ def _rules(tool_path: str, **params: str | None) -> dict[str, Any]:
145
+ return _call("/api/v1/rules/" + tool_path, {k: v for k, v in params.items() if v})
146
+
147
+
148
+ @mcp.tool()
149
+ def rep_required(office: str, act: str | None = None) -> dict[str, Any]:
150
+ """Representation rules of a patent office (office: US, EP, CN, JP, KR, AU, or PCT for the international phase):
151
+ whether and when an applicant must act through a registered agent, each row with its official source and quote.
152
+ act keeps the rows of one act of the vocabulary (rules_index lists it)."""
153
+ return _rules("rep_required/", office=office, act=act)
154
+
155
+
156
+ @mcp.tool()
157
+ def fee_schedule(office: str, as_of: str | None = None) -> dict[str, Any]:
158
+ """Official fees of a patent office in force on as_of (YYYY-MM-DD, default today UTC): filing, search, examination,
159
+ grant, renewal and other fees with their currency, each row with its official source and quote."""
160
+ return _rules("fee_schedule/", office=office, as_of=as_of)
161
+
162
+
163
+ @mcp.tool()
164
+ def route_windows(office: str) -> dict[str, Any]:
165
+ """Generic windows of a patent office, such as the PCT national phase time limit in months from the priority date.
166
+ Never a last day for a specific application; it takes no application number or date."""
167
+ return _rules("route_windows/", office=office)
168
+
169
+
170
+ @mcp.tool()
171
+ def pph_routes(from_office: str, to_office: str) -> dict[str, Any]:
172
+ """Patent Prosecution Highway rows of to_office whose cited source names from_office as a partner office."""
173
+ return _rules("pph_routes/", from_office=from_office, to_office=to_office)
174
+
175
+
176
+ @mcp.tool()
177
+ def ai_use_statement_required(office: str) -> dict[str, Any]:
178
+ """Rows on whether a patent office requires a statement on the use of AI. An empty answer means the dataset holds
179
+ no cited rule for that office; nothing follows from its absence."""
180
+ return _rules("ai_use_statement_required/", office=office)
181
+
182
+
183
+ @mcp.tool()
184
+ def grace_period(office: str) -> dict[str, Any]:
185
+ """What the cited law of an office says about disclosures before filing (the grace period). Citations only: it does
186
+ not say whether any disclosure falls inside the period."""
187
+ return _rules("grace_period/", office=office)
188
+
189
+
190
+ @mcp.tool()
191
+ def rules_changelog(since: str | None = None) -> dict[str, Any]:
192
+ """The rules dataset's releases, newest first, after since (a version x.y.z or a date YYYY-MM-DD)."""
193
+ return _rules("changelog/", since=since)
194
+
195
+
196
+ @mcp.tool()
197
+ def rules_index() -> dict[str, Any]:
198
+ """The rules dataset: its version and date, the offices with their row counts, the tools and the act vocabulary."""
199
+ return _rules("")
200
+
201
+
202
+ @mcp.tool()
203
+ def build_facts() -> dict[str, Any]:
204
+ """The build in service: data_version, as_of, refreshed_at, snapshot hash, superseded versions, table delta."""
205
+ return _call("/api/v1/meta/", keyed=False)
206
+
207
+
208
+ @mcp.tool()
209
+ def search_disclosures(q: str) -> dict[str, Any]:
210
+ """Public records of the PatentRef registry (dated technical disclosures) whose title or abstract match q (web
211
+ search syntax: words, "a phrase", -word, or), newest first, up to 20. Each record carries its permalink
212
+ (https://patentref.io/r/<id>), server_time, bundle_hash and proof_status; the submitter's text is inside
213
+ user_content, as entered. A record shows what was published and when, not a patent or an opinion."""
214
+ return _call("/registry/search", {"q": q.strip()[:200]}, keyed=False)
215
+
216
+
217
+ def main(argv=None):
218
+ ap = argparse.ArgumentParser(prog="patentref-mcp", description="PatentRef MCP server (stdio by default)")
219
+ ap.add_argument("--http", action="store_true", help="serve streamable HTTP instead of stdio")
220
+ ap.add_argument("--host", default="127.0.0.1")
221
+ ap.add_argument("--port", type=int, default=8787)
222
+ a = ap.parse_args(argv)
223
+ if not _key():
224
+ print("patentref-mcp: PATENTREF_API_KEY is not set; keyed tools will answer an error", file=sys.stderr)
225
+ if a.http:
226
+ mcp.settings.host, mcp.settings.port = a.host, a.port
227
+ mcp.run(transport="streamable-http")
228
+ else:
229
+ mcp.run(transport="stdio")
230
+
231
+
232
+ if __name__ == "__main__":
233
+ main()
patentref_mcp/smoke.py ADDED
@@ -0,0 +1,72 @@
1
+ """End-to-end smoke test over stdio: starts the server as a child process, speaks MCP to it (initialize,
2
+ tools/list, check_patent_status, similar_patents) and prints the transcript. The key comes from the
3
+ environment and never appears in the output.
4
+
5
+ python3 -m patentref_mcp.smoke 10000364 [--http http://127.0.0.1:8787/mcp]
6
+ """
7
+ import asyncio
8
+ import json
9
+ import os
10
+ import sys
11
+
12
+
13
+ def _trim(obj, n=1200):
14
+ s = json.dumps(obj, indent=1, default=str)
15
+ return s if len(s) <= n else s[:n] + f"\n... ({len(s)} chars)"
16
+
17
+
18
+ async def run_stdio(pid):
19
+ from mcp import ClientSession, StdioServerParameters
20
+ from mcp.client.stdio import stdio_client
21
+
22
+ params = StdioServerParameters(command=sys.executable, args=["-m", "patentref_mcp.server"], env=dict(os.environ))
23
+ async with stdio_client(params) as (read, write):
24
+ async with ClientSession(read, write) as session:
25
+ await _drive(session, pid, "stdio")
26
+
27
+
28
+ async def run_http(pid, url):
29
+ from mcp import ClientSession
30
+ from mcp.client.streamable_http import streamablehttp_client
31
+
32
+ async with streamablehttp_client(url) as (read, write, _):
33
+ async with ClientSession(read, write) as session:
34
+ await _drive(session, pid, "streamable-http " + url)
35
+
36
+
37
+ async def _drive(session, pid, transport):
38
+ init = await session.initialize()
39
+ print(f"[{transport}] initialize -> server {init.serverInfo.name} {init.serverInfo.version}, protocol {init.protocolVersion}")
40
+ tools = await session.list_tools()
41
+ print(f"[{transport}] tools/list -> {[t.name for t in tools.tools]}")
42
+ for name, args in (("check_patent_status", {"patent_id": pid}),
43
+ ("similar_patents", {"text": "coherent ladar using intra-pixel quadrature detection", "n": 3})):
44
+ res = await session.call_tool(name, args)
45
+ print(f"[{transport}] tools/call {name} {json.dumps(args)} -> isError={res.isError}")
46
+ for c in res.content:
47
+ text = getattr(c, "text", None)
48
+ if text:
49
+ try:
50
+ print(_trim(json.loads(text)))
51
+ except ValueError:
52
+ print(text[:1200])
53
+
54
+
55
+ def main(argv=None):
56
+ argv = list(sys.argv[1:] if argv is None else argv)
57
+ pid = "10000364"
58
+ url = None
59
+ while argv:
60
+ a = argv.pop(0)
61
+ if a == "--http":
62
+ url = argv.pop(0)
63
+ else:
64
+ pid = a
65
+ if url:
66
+ asyncio.run(run_http(pid, url))
67
+ else:
68
+ asyncio.run(run_stdio(pid))
69
+
70
+
71
+ if __name__ == "__main__":
72
+ main()
@@ -0,0 +1,57 @@
1
+ Metadata-Version: 2.4
2
+ Name: patentref-mcp
3
+ Version: 0.4.0
4
+ Summary: MCP server for the PatentRef API: check_patent_status, search_patents, similar_patents, get_claim_tree, get_patent_brief and the rules tools, over stdio or streamable HTTP
5
+ License-Expression: MIT
6
+ Project-URL: Homepage, https://patentref.io/
7
+ Project-URL: Documentation, https://patentref.io/docs/
8
+ Requires-Python: >=3.10
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Requires-Dist: mcp<2,>=1.10
12
+ Requires-Dist: httpx>=0.27
13
+ Dynamic: license-file
14
+
15
+ # patentref-mcp
16
+
17
+ <!-- mcp-name: io.github.patentref/patentref-mcp -->
18
+
19
+ The only free API and MCP tool we know of that returns a US patent's claim tree with element segmentation, antecedent links and character offsets, built by deterministic code, 1976 to now.
20
+
21
+ patentref-mcp is an MCP server for the PatentRef API (https://patentref.io). Each tool sends one HTTPS request to the public API with the key from its environment and returns the API's JSON as the API sent it.
22
+
23
+ ## Run
24
+
25
+ ```
26
+ pip install patentref-mcp
27
+ export PATENTREF_API_KEY=... # a key from https://patentref.io/api/v1/meta/signup/
28
+ patentref-mcp # stdio, what most MCP clients start
29
+ patentref-mcp --http --port 8787 # streamable HTTP at http://127.0.0.1:8787/mcp
30
+ ```
31
+
32
+ Claude Desktop (`claude_desktop_config.json`):
33
+
34
+ ```json
35
+ {"mcpServers": {"patentref": {"command": "patentref-mcp", "env": {"PATENTREF_API_KEY": "..."}}}}
36
+ ```
37
+
38
+ Environment: `PATENTREF_API_KEY` (sent by every tool but `build_facts` and `search_disclosures`), `PATENTREF_BASE` (default `https://patentref.io`), `PATENTREF_TIMEOUT` (seconds, default 30).
39
+
40
+ Check an install: `python -m patentref_mcp.smoke 10000364` starts the server over stdio, lists its tools, makes two tool calls and prints the transcript.
41
+
42
+ ## Tools
43
+
44
+ - `get_claim_tree(patent_id)`: one patent's claims as a tree, from the claim text as the USPTO published it; every part carries start and end offsets into its claim's text. `GET /api/v1/structure/claims/<patent_id>/`
45
+ - `get_patent_brief(patent_id, max_tokens)`: one patent in a fixed order, cut to fit `max_tokens` (300 to 32000, default 2000), each independent claim as its elements with their offsets. `GET /api/v1/structure/brief/<patent_id>/`
46
+ - `check_patent_status(patent_id)`: the status record of one patent, with its basis, as-of date and data version. `GET /api/v1/lapse/status/<patent_id>/`
47
+ - `search_patents(q, f, s, size, after)`: the PatentSearch v1 query grammar. `GET /api/v1/patent/`
48
+ - `similar_patents(text, n)`: the US patents nearest to a title and abstract. `GET /api/v1/lapse/similar`
49
+ - `build_facts()`: the data version and as-of date in service. `GET /api/v1/meta/`
50
+ - `search_disclosures(q)`: public records of the PatentRef registry. `GET /registry/search`
51
+ - `rep_required`, `fee_schedule`, `route_windows`, `pph_routes`, `ai_use_statement_required`, `grace_period`, `rules_changelog`, `rules_index`: rows of patent office rules, each with its source URL and a verbatim quote. `GET /api/v1/rules/`
52
+
53
+ An error from the API comes back as the tool's error text: the HTTP status and the API's `X-Status-Reason`. The server does not retry.
54
+
55
+ ## License
56
+
57
+ MIT, see `LICENSE`. The data the API returns has its own license and attribution lines: https://patentref.io/LICENSES.md
@@ -0,0 +1,9 @@
1
+ patentref_mcp/__init__.py,sha256=cwaCPZZ2I5nmajdl92TJYVlr-3YyYOtqclDi1G1sPl4,75
2
+ patentref_mcp/server.py,sha256=pDVtdUL9RhI3nKqCQ-zCzKPpPo59RfPY9dK2EGZ7B2w,11676
3
+ patentref_mcp/smoke.py,sha256=n1TQjsGYjQp5a-JFtC1IB4dD8coBSVta1fd2qabO4WQ,2531
4
+ patentref_mcp-0.4.0.dist-info/licenses/LICENSE,sha256=C4Dy5LAA2ATG8mv_zQEULn1DVh4bXbSjuj3MRq4kAtQ,1068
5
+ patentref_mcp-0.4.0.dist-info/METADATA,sha256=hfO88s2yALC4yWjK1fKQ6-IF4K7Td9EB5yVj73Jv_N4,3352
6
+ patentref_mcp-0.4.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
7
+ patentref_mcp-0.4.0.dist-info/entry_points.txt,sha256=gc_K5jzy8qhPTyZGoulz8lBddPb9D_LXYZNo18I42Ks,60
8
+ patentref_mcp-0.4.0.dist-info/top_level.txt,sha256=HdpDXu8UkXiqczNV9W5gQqXupHbAYqyK_BiHfqyhAs8,14
9
+ patentref_mcp-0.4.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ patentref-mcp = patentref_mcp.server:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Aaron Baker
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 @@
1
+ patentref_mcp