Skip to content
Back to search

claude-patent-creator

MarketplaceWorks with Claude CodeGitHubIncomplete

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/robthepcguy--claude-patent-creator/badge.svg)](/listings/robthepcguy--claude-patent-creator)

HTML

<a href="/listings/robthepcguy--claude-patent-creator"><img src="/api/listings/robthepcguy--claude-patent-creator/badge.svg" alt="findsafeskills safety rating" /></a>

Install

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

This takes about an hour, most of it waiting while the tool downloads the patent rulebook and builds its search index. You type a handful of lines; nothing here needs programming.

What you need first

| You need | How to check or get it | |---|---| | **Claude Code** with a paid Claude plan | Anthropic's AI assistant. [Install it](https://claude.com/claude-code), sign in, and open it once. | | **A terminal** | The window where you type commands. Mac: press Cmd+Space, type `Terminal`, press Enter. Windows: press Start, type `PowerShell`, press Enter. | | **Python 3.10 to 3.13** | In the terminal, type `python3 --version` (Mac/Linux) or `py --version` (Windows). If it says 3.9 or older, or "not found", install Python 3.13 from [python.org/downloads](https://www.python.org/downloads/) and open a new terminal. On Windows, tick "Add python.exe to PATH" in the installer. | | **git** | Type `git --version`. On a Mac that has never used it, a box offers to install "command line developer tools": click Install. Windows: install [Git for Windows](https://git-scm.com/download/win) (Claude Code needs it on Windows anyway). | | **About 4 GB of free disk space** | The tool itself is about 2 GB; the rulebook and index add about 1 GB. |

Step 1: Install the tool

Copy these lines into the terminal one at a time, pressing Enter after each. They make a private folder for the tool (a "virtual environment"), so it can't disturb anything else on your computer.

**Mac or Linux:**

cd ~
python3 -m venv patent-creator-venv
patent-creator-venv/bin/pip install git+https://github.com/RobThePCGuy/Claude-Patent-Creator.git
patent-creator-venv/bin/patent-creator setup

**Windows (PowerShell):**

cd ~
py -m venv patent-creator-venv
.\patent-creator-venv\Scripts\pip install git+https://github.com/RobThePCGuy/Claude-Patent-Creator.git
.\patent-creator-venv\Scripts\patent-creator setup

The install line takes about a minute. `setup` then runs for 5 to 45 minutes (45 on a laptop without an NVIDIA graphics card, including Apple Silicon Macs). It asks three questions:

- **Delete the PDF files?** Either answer is fine. The search runs on the index it built; the PDFs are only needed to rebuild it. - **Install Graphviz?** Say yes if you want patent drawings. It's a free program the diagram tools need. - **Set up BigQuery?** Say no for now. It's an optional patent search that needs a Google Cloud account; Step 3 covers the easier option.

It finishes by connecting itself to Claude Code and testing that connection. If you see **Setup Complete!**, go on. If it says Claude Code is **not connected**, the lines above that message say why.

Step 2: Add the guided workflows to Claude Code

Step 1 gives Claude the tools. This step adds the guided workflows, like `/create-patent`. Open Claude Code and type these two lines into Claude (not the terminal):

/plugin marketplace add RobThePCGuy/Claude-Patent-Creator
/plugin install claude-patent-creator-standalone@claude-patent-creator

Quit Claude Code completely and open it again. Then ask it:

> Search MPEP for claim definiteness requirements

You should get rule excerpts, each labeled with the MPEP chapter, the PDF file and the page it came from. That means everything is connected.

Step 3: Turn on patent search (free key)

Rule search, claim checks and research-paper search work now with no keys, and so do drawings if you said yes to Graphviz. The recommended way to search existing **patents** uses a free SerpApi key:

1. Sign up at [serpapi.com](https://serpapi.com/users/sign_up) (250 free searches a month). 2. Copy your key from [serpapi.com/manage-api-key](https://serpapi.com/manage-api-key). 3. In the terminal, save it (replace `YOUR_KEY`): - Mac/Linux: `~/patent-creator-venv/bin/patent-creator config set SERPAPI_API_KEY "YOUR_KEY"` - Windows: `.\patent-creator-venv\Scripts\patent-creator config set SERPAPI_API_KEY "YOUR_KEY"` (run `cd ~` first)

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

.claude-plugin/marketplace.json · Manifest · 36 lines
  1. {
  2. "name": "claude-patent-creator",
  3. "owner": {
  4. "name": "RobThePCGuy"
  5. },
  6. "metadata": {
  7. "description": "USPTO patent creation and analysis system with hybrid RAG search, worldwide Google Patents search, automated compliance checking, prior art search, and diagram generation.",
  8. "version": "1.1.17"
  9. },
  10. "plugins": [
  11. {
  12. "name": "claude-patent-creator-standalone",
  13. "source": "./",
  14. "description": "Patent drafting, prior-art search, USPTO rule search and compliance checks for Claude Code. Needs the companion patent-creator tool (README Quick Start, Step 1) for search and checks.",
  15. "version": "1.1.17",
  16. "author": {
  17. "name": "RobThePCGuy"
  18. },
  19. "homepage": "https://github.com/RobThePCGuy/Claude-Patent-Creator",
  20. "repository": "https://github.com/RobThePCGuy/Claude-Patent-Creator",
  21. "license": "MIT",
  22. "keywords": [
  23. "patent",
  24. "uspto",
  25. "mpep",
  26. "patent-review",
  27. "claims-analysis",
  28. "prior-art",
  29. "patent-search",
  30. "bigquery",
  31. "diagrams"
  32. ],
  33. "category": "legal"
  34. }
  35. ]
  36. }
README.md · README · 631 lines
  1. # Claude Patent Creator
  2. [![MIT License](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
  3. [![Python 3.10-3.13](https://img.shields.io/badge/python-3.10--3.13-blue.svg)](https://www.python.org/downloads/)
  4. [![MCP Server](https://img.shields.io/badge/MCP-Python%20SDK%202.x-purple.svg)](https://github.com/modelcontextprotocol/python-sdk)
  5. [![PyTorch](https://img.shields.io/badge/PyTorch-2.9+-red.svg)](https://pytorch.org/)
  6. [![Status](https://img.shields.io/badge/status-beta%20(WIP)-orange.svg)](#project-status)
  7. **An AI-powered patent creation and analysis system for Claude Code.**
  8. > **Private beta:** Patent Creator Studio puts these tools in a desktop app for Mac and Windows, and I'm looking for testers. [Join here](https://github.com/RobThePCGuy/Claude-Patent-Creator/discussions/121).
  9. I built this because I needed to file a patent myself. I used AI to build the system, used the system to file the patent, and it worked. Now it's open source so anyone can use it. You do not need to be a lawyer or a programmer. If you can describe your idea in a chat window, you can use this.
  10. In plain terms, this tool lets you:
  11. - **Ask patent-rule questions in plain English.** "Do my claims have to be numbered?" "How long can the abstract be?" You get the actual rule, with a citation, in about a second. (Under the hood it searches the MPEP, the examiner's rulebook, plus the patent statutes and regulations.)
  12. - **Find out whether your idea is actually new.** Search more than 100 million existing patents worldwide for anything close to your invention. This is called a *prior art* search, and it is the single most important step: it is how you learn whether a patent is even worth pursuing.
  13. - **Get your draft checked before a human ever bills you an hour.** The tool reads your claims and application the way an examiner would and flags the mechanical problems: unclear wording, missing sections, an abstract that is too long. It also tells you which checks it *did not* run, so a clean report means what it says.
  14. - **Make the drawings.** Patent-style diagrams and flowcharts from a description, no design software.
  15. - **Go from "here is my idea" to a reviewable draft application.** A guided workflow takes your description (or even your source code), hunts for prior art, drafts claims and a specification, checks everything, and hands you a package a patent professional can review quickly, for US or European filing.
  16. New to the vocabulary? Every term this page uses is explained in the [Glossary](#glossary) in plain English.
  17. ---
  18. ## Read this first: what this tool will and will not do
  19. This tool is built for people who cannot afford a mistake, so it is honest to a fault. Know what you are getting:
  20. - **It will tell you "no."** If the search finds your idea already exists, the tool's job is to show you the evidence and save you the filing fee, not to flatter you into spending money. A well-reasoned "this is not new, and here is why" is the tool working, not failing.
  21. - **It never says "verified" loosely.** Every automated check reports what it ran *and what it skipped*. If a report looks clean, you can trust that the words mean exactly what they say.
  22. - **It does not file anything for you.** You review, you decide, you file. The tool prepares; you commit.
  23. - **It is not a lawyer and does not give legal advice.** What it produces is a well-prepared draft plus organized evidence, built so that a patent professional's review is fast and cheap instead of slow and expensive. For anything you intend to file, have a registered patent practitioner look at it. The point of this tool is to make that look-over affordable, not to skip it.
  24. - **Some judgments are human-only.** Whether your invention is "non-obvious" and whether it is the kind of thing patent law protects at all are legal judgments no software makes reliably. The tool arms you for those conversations; it does not have them for you.
  25. ---
  26. ## Table of Contents
  27. - [What this tool will and will not do](#read-this-first-what-this-tool-will-and-will-not-do)
  28. - [Quick Start](#quick-start)
  29. - [What Can I Actually Do With This?](#what-can-i-actually-do-with-this)
  30. - [How It Works](#how-it-works)
  31. - [What Setup Does](#what-setup-does)
  32. - [CLI Commands](#cli-commands)
  33. - [MCP Tools Reference](#mcp-tools-reference)
  34. - [Skills, Agents, and Slash Commands](#skills-agents-and-slash-commands)
  35. - [Configuration](#configuration)
  36. - [Requirements](#requirements)
  37. - [Architecture](#architecture)
  38. - [Performance](#performance)
  39. - [Known Issues](#known-issues)
  40. - [Glossary](#glossary)
  41. - [Roadmap](#roadmap)
  42. - [Contributing](#contributing)
  43. - [Credits](#credits)
  44. - [License](#license)
  45. ---
  46. ## Quick Start
  47. This takes about an hour, most of it waiting while the tool downloads the patent rulebook and builds its search index. You type a handful of lines; nothing here needs programming.
  48. ### What you need first
  49. | You need | How to check or get it |
  50. |---|---|
  51. | **Claude Code** with a paid Claude plan | Anthropic's AI assistant. [Install it](https://claude.com/claude-code), sign in, and open it once. |
  52. | **A terminal** | The window where you type commands. Mac: press Cmd+Space, type `Terminal`, press Enter. Windows: press Start, type `PowerShell`, press Enter. |
  53. | **Python 3.10 to 3.13** | In the terminal, type `python3 --version` (Mac/Linux) or `py --version` (Windows). If it says 3.9 or older, or "not found", install Python 3.13 from [python.org/downloads](https://www.python.org/downloads/) and open a new terminal. On Windows, tick "Add python.exe to PATH" in the installer. |
  54. | **git** | Type `git --version`. On a Mac that has never used it, a box offers to install "command line developer tools": click Install. Windows: install [Git for Windows](https://git-scm.com/download/win) (Claude Code needs it on Windows anyway). |
  55. | **About 4 GB of free disk space** | The tool itself is about 2 GB; the rulebook and index add about 1 GB. |
  56. ### Step 1: Install the tool
  57. Copy these lines into the terminal one at a time, pressing Enter after each. They make a private folder for the tool (a "virtual environment"), so it can't disturb anything else on your computer.
  58. **Mac or Linux:**
  59. ```bash
  60. cd ~
  61. python3 -m venv patent-creator-venv
  62. patent-creator-venv/bin/pip install git+https://github.com/RobThePCGuy/Claude-Patent-Creator.git
  63. patent-creator-venv/bin/patent-creator setup
  64. ```
  65. **Windows (PowerShell):**
  66. ```powershell
  67. cd ~
  68. py -m venv patent-creator-venv
  69. .\patent-creator-venv\Scripts\pip install git+https://github.com/RobThePCGuy/Claude-Patent-Creator.git
  70. .\patent-creator-venv\Scripts\patent-creator setup
  71. ```
  72. The install line takes about a minute. `setup` then runs for 5 to 45 minutes (45 on a laptop without an NVIDIA graphics card, including Apple Silicon Macs). It asks three questions:
  73. - **Delete the PDF files?** Either answer is fine. The search runs on the index it built; the PDFs are only needed to rebuild it.
  74. - **Install Graphviz?** Say yes if you want patent drawings. It's a free program the diagram tools need.
  75. - **Set up BigQuery?** Say no for now. It's an optional patent search that needs a Google Cloud account; Step 3 covers the easier option.
  76. It finishes by connecting itself to Claude Code and testing that connection. If you see **Setup Complete!**, go on. If it says Claude Code is **not connected**, the lines above that message say why.
  77. ### Step 2: Add the guided workflows to Claude Code
  78. Step 1 gives Claude the tools. This step adds the guided workflows, like `/create-patent`. Open Claude Code and type these two lines into Claude (not the terminal):
  79. ```
  80. /plugin marketplace add RobThePCGuy/Claude-Patent-Creator
  81. /plugin install claude-patent-creator-standalone@claude-patent-creator
  82. ```
  83. Quit Claude Code completely and open it again. Then ask it:
  84. > Search MPEP for claim definiteness requirements
  85. You should get rule excerpts, each labeled with the MPEP chapter, the PDF file and the page it came from. That means everything is connected.
  86. ### Step 3: Turn on patent search (free key)
  87. Rule search, claim checks and research-paper search work now with no keys, and so do drawings if you said yes to Graphviz. The recommended way to search existing **patents** uses a free SerpApi key:
  88. 1. Sign up at [serpapi.com](https://serpapi.com/users/sign_up) (250 free searches a month).
  89. 2. Copy your key from [serpapi.com/manage-api-key](https://serpapi.com/manage-api-key).
  90. 3. In the terminal, save it (replace `YOUR_KEY`):
  91. - Mac/Linux: `~/patent-creator-venv/bin/patent-creator config set SERPAPI_API_KEY "YOUR_KEY"`
  92. - Windows: `.\patent-creator-venv\Scripts\patent-creator config set SERPAPI_API_KEY "YOUR_KEY"` (run `cd ~` first)
  93. 4. Restart Claude Code.
  94. If Google Patents is not ready, configured EPO OPS is a patent-search fallback: save `EPO_OPS_KEY` and `EPO_OPS_SECRET` from [developers.epo.org](https://developers.epo.org/) with the same `config set` command, restart, and run `check_epo_api_status`. OPS searches worldwide titles/abstracts and classifications; full text is available for selected publications. BigQuery is another optional provider. USPTO ODP searches application metadata and is a supplement only.
  95. Now ask: *"Is my idea of a self-heating coffee mug new?"*
  96. ### What it costs
  97. | Part | Cost |
  98. |---|---|
  99. | Claude Code | Your paid Claude plan. This is the only required cost. |
  100. | Rule search, claim and formality checks, drawings | Free, runs on your computer |
  101. | Research-paper search (OpenAlex, arXiv, Semantic Scholar) | Free, no key needed |
  102. | Patent search through SerpApi (Google Patents) | Free for 250 searches a month |
  103. | Patent search through BigQuery (optional) | Free for the first 1 TB of searching each month; Google charges after that only if you add billing |
  104. ### If something goes wrong
  105. Run the health check. It says what's working and what to fix:
  106. - Mac/Linux: `~/patent-creator-venv/bin/patent-creator health`
  107. - Windows: `.\patent-creator-venv\Scripts\patent-creator health` (from `cd ~`)
  108. To test the connection to Claude Code, starting the tool exactly the way Claude does:
  109. - Mac/Linux: `~/patent-creator-venv/bin/patent-creator verify-config`
  110. - Windows: `.\patent-creator-venv\Scripts\patent-creator verify-config` (from `cd ~`)
  111. <details>
  112. <summary><strong>Other ways to install</strong></summary>
  113. **Let Claude do the install.** After Step 2, type `/claude-patent-creator-standalone:setup-patent-system` in Claude Code. Claude makes the private folder, installs and runs setup for you. Skip this if you already did Step 1.
  114. **From a copy of the code** (for people changing the code):
  115. ```bash
  116. git clone https://github.com/RobThePCGuy/Claude-Patent-Creator.git
  117. cd Claude-Patent-Creator
  118. python3 -m venv venv
  119. venv/bin/pip install -e .
  120. venv/bin/patent-creator setup
  121. ```
  122. On a Mac, a bare `pip install ...` outside a private folder fails with `externally-managed-environment`. That's macOS protecting its own Python. Use the steps above; don't use `--break-system-packages`.
  123. </details>
  124. ---
  125. ## What Can I Actually Do With This?
  126. Here are some real examples. You can type these directly in Claude Code and the right skill or tool kicks in automatically. Say it in your own words; the "what to say" column is a starting point, not a required incantation.
  127. | What you want to do | What to say | What happens |
  128. |---|---|---|
  129. | Find out if a rule applies to you | "Search MPEP for claim definiteness requirements", or just "do my claims have to be written a certain way?" | The tool searches the examiner's rulebook and returns the relevant sections, with citations you can read yourself |
  130. | See if your idea already exists | "Search for patents about [your idea]", e.g. "self-heating coffee mug" | Searches 100M+ existing patents and shows you the closest matches, so you know what you're up against (needs the free key from Quick Start Step 3) |
  131. | Get your draft claims checked | "Review these claims" (paste them in) | Flags unclear wording, subjective terms and structural problems, the mechanical mistakes an examiner rejects first, and says which checks it skipped |
  132. | Check a whole application | `/full-review` | Runs the claims, description, and formatting checks together and reports everything at once |
  133. | Go from idea to draft application | `/create-patent` | A guided workflow: describe the invention, the tool searches prior art, drafts, checks, and assembles a reviewable package. Plan on 2.5 to 4.5 hours of back-and-forth; the result is Markdown and SVG files you convert to DOCX/PDF before filing |
  134. | Make a drawing | "Create a block diagram showing [your system]" | Produces a patent-style figure, no design software needed |
  135. | Dig deep on whether your idea is new | "Conduct a prior art search for [your invention]" | A thorough multi-angle hunt through existing patents, with an honest verdict on what it found |
  136. ---
  137. ## How It Works
  138. *Everything from here down gets progressively more technical. You do not need any of it to use the tool: the sections above plus the [Glossary](#glossary) are enough. This part is for developers, patent professionals, and the curious.*
  139. The system has two modes that can work independently or together:
  140. **MCP Server** is the engine. It exposes 20+ tools that any MCP-compatible client (Claude Code, Claude Desktop, etc.) can call programmatically. These tools handle search, analysis, and diagram generation.
  141. **Claude Code Plugin** adds the interactive layer. Skills activate automatically based on what you're doing. Agents handle long-running tasks in the background. Slash commands give you quick access to common workflows.
  142. Under the hood, patent regulation search uses a hybrid approach: FAISS vector search finds semantically similar content, BM25 lexical search catches exact terminology matches, and a cross-encoder reranker sorts the combined results by relevance. Patent keyword search goes through Google Patents via SerpApi (free key, recommended) with EPO OPS as a worldwide title/abstract and classification fallback, or optionally Google BigQuery's public patent dataset.
  143. ```
  144. You (Claude Code) ──> MCP Server ──> Search / Analysis / Diagrams
  145. │
  146. ┌──────────────┼──────────────┐
  147. v v v
  148. MPEP/USC/CFR Google Patents Graphviz
  149. EPC/PCT (SerpApi) or (diagrams)
  150. (hybrid RAG) EPO OPS / BigQuery
  151. + papers (OpenAlex,
  152. arXiv, Semantic Scholar)
  153. ```
  154. ---
  155. ## What Setup Does
  156. `patent-creator setup` runs these steps. Running it again is safe: it skips anything already done.
  157. 1. Checks your hardware. On an NVIDIA graphics card it installs the GPU version of PyTorch and restarts itself. Apple Silicon and other computers build on the CPU, which is faster than Apple's GPU for this job.
  158. 2. Downloads the MPEP, 35 USC and 37 CFR from the USPTO, and the EPO and PCT rules (about 500 MB).
  159. 3. Builds the search index (FAISS + BM25). This is the long step.
  160. 4. Offers to delete the downloaded PDFs. The index keeps working either way.
  161. 5. Asks before installing Graphviz for the diagram tools. It never installs it without a yes.
  162. 6. Looks for existing Google Cloud sign-in for the optional BigQuery search.
  163. 7. Registers the tool with Claude Code, then starts it the way Claude will and checks it answers. It only reports success after that check passes.
  164. Data lives in `~/.local/share/claude-patent-creator/data` (Mac/Linux) or `%APPDATA%\claude-patent-creator\data` (Windows); `PATENT_DATA_DIR` moves it. To load the plugin from a local copy of the code instead of the marketplace: `claude --plugin-dir ./Claude-Patent-Creator`.
  165. ---
  166. ## CLI Commands
  167. Run these in a terminal. If you followed the Quick Start, put `~/patent-creator-venv/bin/` (Mac/Linux) or `.\patent-creator-venv\Scripts\` (Windows, from `cd ~`) in front of `patent-creator`.
  168. ```bash
  169. patent-creator setup # Full setup: downloads, builds index, connects to Claude Code
  170. patent-creator setup --rebuild # Same, but rebuilds the search index from scratch
  171. patent-creator health # What's working and what isn't
  172. patent-creator status # Same as health
  173. patent-creator verify-config # Starts the tool the way Claude Code does and checks it answers
  174. patent-creator serve # Run the MCP server by hand
  175. patent-creator config list # Show every setting and where its value comes from
  176. patent-creator config set KEY VALUE # Save a setting or key (e.g. SERPAPI_API_KEY)
  177. patent-creator config unset KEY # Remove a saved setting
  178. patent-creator config path # Where saved settings live
  179. patent-creator config --gui # Settings window (needs Python's Tkinter)
  180. patent-creator rebuild-index # Rebuild the MPEP search index
  181. patent-creator download-mpep # Download MPEP PDFs only
  182. patent-creator download-all # Download all sources (MPEP + 35 USC + 37 CFR)
  183. patent-creator check-bigquery # Test BigQuery connection
  184. ```
  185. ---
  186. ## MCP Tools Reference
  187. ### Search
  188. | Tool | What it does |
  189. |---|---|
  190. | `search_mpep` | Hybrid RAG search across MPEP, 35 USC, and 37 CFR with filters |
  191. | `get_mpep_section` | Pull the text of an MPEP section (e.g. 608.01(b)) from its chapter; says when boundaries are approximate or the text is cut off |
  192. | `search_patents_google` | Full-text keyword search worldwide, claims included (recommended; free SerpApi key, 250 searches/month) |
  193. | `search_patents_bigquery` | Keyword search fallback when no SerpApi key is set (~$2 a search past the free monthly TiB) |
  194. | `search_non_patent_literature` | Papers and preprints as prior art (OpenAlex, arXiv, Semantic Scholar), free with no key, filter by priority date |
  195. | `get_patent_bigquery` | Get details on a specific patent (claims by default; abstract/description opt-in) |
  196. | `get_patents_bigquery` | Get details on up to 50 patents in one query, same cost as one |
  197. | `search_patents_by_cpc_bigquery` | Search by CPC classification code |
  198. | `search_uspto_api` | Search ODP application metadata; supplement only, not claims/description full text |
  199. | `get_uspto_patent` | Get patent details from USPTO |
  200. | `get_recent_uspto_patents` | Pull recent filings |
  201. | `search_patent_law` | Law search across US (MPEP/USC/CFR), EPO (EPC/Guidelines) and PCT sources |
  202. | `search_patents_by_ipc_bigquery` | Search by IPC classification code |
  203. | `search_patent_family_bigquery` | Every publication in a patent family, across countries |
  204. | `search_epo_patents` | Worldwide title/abstract and classification search through EPO OPS (key and secret; no implicit EP filter) |
  205. | `get_epo_patent` | Bibliographic data and available claims/description through EPO OPS; full-text coverage varies |
  206. | `get_epo_patent_family` | Patent family members through EPO OPS |
  207. ### Analysis
  208. | Tool | What it does |
  209. |---|---|
  210. | `review_patent_claims` | 35 USC 112(b) compliance check (definiteness, antecedent basis, structure) |
  211. | `review_specification` | 35 USC 112(a) written-description and enablement heuristics; best mode requires manual review |
  212. | `check_formalities` | MPEP 608 compliance (abstract, title, drawings, required sections) |
  213. | `review_epo_claims` | Art. 84 EPC claim check (clarity, support, two-part form) |
  214. | `review_epo_specification` | Art. 83 EPC sufficiency and Rule 42 sections |
  215. | `check_epo_formalities` | EPO formalities, Rules 42-49 EPC |
  216. | `check_pct_formalities` | PCT formalities, Rules 5-12 |
  217. | `check_package` | Whole-package consistency: stale verification stamps, claim-count disagreements, status contradictions, commentary inside filing copies, date errors |
  218. ### Generation
  219. | Tool | What it does |
  220. |---|---|
  221. | `render_diagram` | Generate patent-style diagrams from Graphviz DOT code |
  222. | `create_flowchart` | Build a flowchart from a list of steps and connections |
  223. | `create_block_diagram` | Build a block diagram from components and relationships |
  224. | `add_diagram_references` | Add patent reference numbers to an existing SVG diagram |
  225. | `get_diagram_templates` | List available diagram templates |
  226. ### System
  227. | Tool | What it does |
  228. |---|---|
  229. | `check_bigquery_status` | BigQuery configuration status |
  230. | `check_google_patents_status` | Whether SerpApi patent search is set up and how many searches are left |
  231. | `check_diagram_tools_status` | Graphviz availability |
  232. | `check_uspto_api_status` | USPTO API connectivity |
  233. | `check_epo_api_status` | EPO OPS credentials and authentication readiness |
  234. Search index statistics are available as the MCP resource `mpep://index/stats`.
  235. ---
  236. ## Skills, Agents, and Slash Commands
  237. ### Skills (activate automatically)
  238. You don't need to call these directly. Just describe what you want to do and the right skill kicks in.
  239. | Skill | When it activates | What it brings |
  240. |---|---|---|
  241. | **setup-assistant** | Installing, configuring, or troubleshooting | Full setup lifecycle guidance |
  242. | **patent-reviewer** | Reviewing a complete application for compliance | Comprehensive review (claims + spec + formalities) |
  243. | **patent-claims-analyzer** | Reviewing claims specifically for 35 USC 112(b) | Deep-dive claims analysis (definiteness, antecedent basis, structure) |
  244. | **patent-search** | Searching patents or prior art | Google Patents, EPO OPS fallback and optional BigQuery workflows |
  245. | **bigquery-patent-search** | Quick BigQuery-only patent search | Keyword, CPC, and patent detail retrieval across 100M+ patents |
  246. | **mpep-search** | Finding MPEP sections or regulations | Hybrid RAG search |
  247. | **patent-diagram-generator** | Creating technical diagrams | Flowcharts, block diagrams, system architectures via Graphviz |
  248. | **patent-application-creator** | Drafting a patent application interactively | Guided end-to-end workflow (prior art, claims, spec, diagrams, compliance) |
  249. | **prior-art-search** | Novelty or freedom-to-operate analysis | 7-step prior art discovery methodology |
  250. | **index-manager** | Building or rebuilding the search index | MPEP index lifecycle management |
  251. | **development-assistant** | Adding features or creating tools | Development workflows and patterns |
  252. | **troubleshooting-assistant** | Something's broken | Systematic 6-step diagnostics |
  253. | **testing-assistant** | Running tests or validation | Test suite execution |
  254. | **epc-search** | European or PCT law questions | Search of the EPC, EPO Guidelines and PCT rules |
  255. | **epo-patent-analyzer** | Checking an application for EPO filing | Art. 84 and Art. 83 EPC checks |
  256. | **epo-patent-search** | Searching European patents | Worldwide EPO OPS search; Google Patents/BigQuery support an explicit EP filter |
  257. | **pct-application** | Preparing an international (PCT) application | PCT Rules 5-12, unity of invention, national phase deadlines |
  258. ### Agents (long-running, work independently)
  259. These run in the background while you keep working on other things. There are 13 in `agents/`; these two are the ones you'll start yourself.
  260. | Agent | What it does | How long | Output |
  261. |---|---|---|---|
  262. | **patent-creator** | Drafts a complete USPTO-ready application | 55-80 min | Specification, claims, abstract, diagrams, validation report |
  263. | **prior-art-searcher** | Comprehensive prior art search | 15-30 min | Patentability report, top 10 prior art, claim strategy, IDS list |
  264. To use them: "Create a patent for [your invention], use the patent-creator agent"
  265. ### Slash Commands
  266. ```
  267. /create-patent # Guided US application, idea to draft (2.5-4.5 hours)
  268. /create-epo-patent # Guided European application
  269. /search-prior-art # Prior art search with novelty analysis
  270. /search-epo # European patent search
  271. /full-review # Parallel review (claims + spec + formalities)
  272. /review-claims # Claims-only 35 USC 112(b) analysis
  273. /review-specification # Specification-only 35 USC 112(a) analysis
  274. /review-formalities # MPEP 608 formalities check
  275. /review-epo-claims # Art. 84 EPC claims check
  276. /review-epo-formalities # EPO formalities (Rules 42-49 EPC)
  277. /check-pct-formalities # PCT formalities (Rules 5-12)
  278. /configure-bigquery # Set up the optional BigQuery search
  279. /rebuild-index # Rebuild the rulebook search index
  280. /test-system # Run the system checks
  281. ```
  282. Installed from the marketplace, each command is also available with the plugin prefix, for example `/claude-patent-creator-standalone:create-patent`.
  283. ---
  284. ## Configuration
  285. Save settings and keys with the `config` command. They go in one file, `~/.config/claude-patent-creator/config.json` (Mac/Linux) or `%APPDATA%\claude-patent-creator\config.json` (Windows), stored as plain text and readable only by you on Mac/Linux. Restart Claude Code after changing one.
  286. ```bash
  287. patent-creator config set SERPAPI_API_KEY "your-key"
  288. patent-creator config list
  289. ```
  290. | Setting | What it's for | Where to get it |
  291. |---|---|---|
  292. | `SERPAPI_API_KEY` | Google Patents search (recommended) | Free, 250 searches a month: [serpapi.com](https://serpapi.com/users/sign_up) |
  293. | `GOOGLE_CLOUD_PROJECT` | BigQuery patent search (optional) | Your Google Cloud project ID, see below |
  294. | `OPENALEX_API_KEY` | More daily paper searches (works without it) | Free: [openalex.org](https://openalex.org/settings/api-key) |
  295. | `SEMANTIC_SCHOLAR_API_KEY` | Steadier Semantic Scholar paper search (works without it) | Free, by request: [semanticscholar.org](https://www.semanticscholar.org/product/api#api-key-form) |
  296. | `EPO_OPS_KEY`, `EPO_OPS_SECRET` | Worldwide patent search and available full text | Free registration: [developers.epo.org](https://developers.epo.org) |
  297. | `USPTO_API_KEY` | USPTO Open Data Portal search | [data.uspto.gov](https://data.uspto.gov/myodp) |
  298. | `ANTHROPIC_API_KEY`, `OPENAI_API_KEY` | Only for HyDE query expansion with `HYDE_BACKEND=api` and `PATENT_MPEP_USE_HYDE=true`. Install the optional `llm` extra or run your environment's Python with `-m pip install anthropic openai` first. HyDE is off by default | Your API account |
  299. | `PATENT_LOG_LEVEL`, `PATENT_LOG_FORMAT` | Server logging detail and format | `INFO`; format `json` for the server and readable lines for the `patent-creator` command unless you set it |
  300. | `PATENT_MPEP_DEVICE` | Force `cpu` or `gpu` for the index build | Detected automatically |
  301. | `PATENT_EMBED_BATCH_SIZE` | Lower it (16 or 8) if the GPU runs out of memory while building the index | 256 on an NVIDIA GPU, 32 otherwise |
  302. | `PATENT_DATA_DIR` | Move the downloaded data and index | Default shown in [What Setup Does](#what-setup-does) |
  303. `patent-creator config list` shows every setting. If you work from a copy of the code, a `.env` file in that folder works too (see `.env.example`); saved settings fill in anything `.env` and your environment leave unset.
  304. <details>
  305. <summary><strong>Setting up BigQuery (optional, for patent search)</strong></summary>
  306. BigQuery searches Google's public patent dataset directly. It needs a Google Cloud project, but not a credit card: the [BigQuery sandbox](https://cloud.google.com/bigquery/docs/sandbox) works without a billing account and includes 1 TB of searching a month. If you add billing, searches past that are charged; the tool refuses any single search that would scan more than its cap (350 GiB by default), so one search can't run up a large bill.
  307. ```bash
  308. # 1. Install Google Cloud SDK
  309. # https://cloud.google.com/sdk/docs/install
  310. # 2. Authenticate
  311. gcloud auth application-default login
  312. # 3. Set quota project (replace with your project ID)
  313. gcloud auth application-default set-quota-project your-project-id
  314. # 4. Save your project ID
  315. patent-creator config set GOOGLE_CLOUD_PROJECT your-project-id
  316. # 5. Test it
  317. patent-creator check-bigquery
  318. ```
  319. </details>
  320. <details>
  321. <summary><strong>Windows-specific setup notes</strong></summary>
  322. **Git Bash is required** for the `claude mcp add` command on Windows. Install [Git for Windows](https://git-scm.com/download/win) and set the path:
  323. ```bash
  324. # PowerShell, if setup can't find Git Bash on its own
  325. $env:CLAUDE_CODE_GIT_BASH_PATH="C:\Program Files\Git\bin\bash.exe"
  326. ```
  327. **Use forward slashes in MCP config paths.** The setup wizard handles this, but if you're configuring manually:
  328. ```bash
  329. # Correct
  330. claude mcp add ... -- "C:/Users/YourName/venv/Scripts/python.exe"
  331. # Wrong (will fail)
  332. claude mcp add ... -- "C:\Users\YourName\venv\Scripts\python.exe"
  333. ```
  334. </details>
  335. ---
  336. ## Requirements
  337. - **Python:** 3.10 to 3.13. CI tests 3.11; the full install has been walked end to end on 3.13 (macOS, Apple Silicon). 3.14 is untested.
  338. - **RAM:** 8 GB (16 GB makes the index build more comfortable)
  339. - **Disk:** about 4 GB free: about 2 GB for the tool and its libraries, 0.5 GB for the language models it downloads, about 1 GB for the rulebook and index
  340. - **Claude Code** with a paid Claude plan
  341. Optional:
  342. - **NVIDIA GPU** with CUDA 12.8: builds the index several times faster. Apple Silicon builds on the CPU.
  343. - **Graphviz:** a free program the diagram tools need (`brew install graphviz`, `winget install graphviz`, or `sudo apt-get install graphviz`). Setup offers to install it.
  344. - **Google Cloud project:** for the optional BigQuery search.
  345. <details>
  346. <summary><strong>Full dependency list</strong></summary>
  347. | Package | Version | Purpose |
  348. |---|---|---|
  349. | mcp | >=2.0.0, <3.0.0 | MCP Python SDK (MCPServer) |
  350. | sentence-transformers | >=5.1.2, <7.0.0 | Text embeddings |
  351. | faiss-cpu | >=1.13.2 | Vector similarity search |
  352. | numpy | >=1.26.0, <3.0.0 | Array operations |
  353. | rank-bm25 | >=0.2.2 | Lexical search |
  354. | transformers | >=4.57.6, <6.0.0 | HuggingFace models |
  355. | google-cloud-bigquery | >=3.41.0 | Patent search |
  356. | pydantic | >=2.12.5 | Data validation |
  357. | graphviz | >=0.21 | Diagram generation |
  358. | PyMuPDF | >=1.26.0 | PDF processing |
  359. See `pyproject.toml` for the complete list.
  360. </details>
  361. ---
  362. ## Architecture
  363. ```
  364. claude-patent-creator/
  365. ├── .claude-plugin/ # Plugin manifest and marketplace config
  366. ├── mcp_server/ # Core MCP server
  367. │ ├── server.py # MCPServer entry point
  368. │ ├── mpep_search.py # Hybrid RAG search engine
  369. │ ├── bigquery_search.py # BigQuery patent search
  370. │ ├── claims_analyzer.py # 35 USC 112(b) analyzer
  371. │ ├── specification_analyzer.py # 112(a) analyzer
  372. │ ├── formalities_checker.py # MPEP 608 checker
  373. │ ├── diagram_generator.py # Graphviz diagrams
  374. │ ├── tools/ # MCP tool definitions
  375. │ └── index/ # FAISS + BM25 index (git-ignored)
  376. ├── skills/ # Claude Code skills (17)
  377. ├── agents/ # Autonomous agents (13)
  378. ├── commands/ # Slash commands (16)
  379. ├── hooks/ # Event-driven automation
  380. ├── scripts/ # Testing and utilities
  381. ├── docs/ # Additional documentation
  382. ├── pdfs/ # Downloaded MPEP PDFs (git-ignored)
  383. └── CLAUDE.md # Full project documentation
  384. ```
  385. For the complete architecture documentation, development workflows, and troubleshooting guides, see [CLAUDE.md](CLAUDE.md).
  386. ---
  387. ## Performance
  388. | Operation | Time | Notes |
  389. |---|---|---|
  390. | **MPEP Search** | 50-200ms | Hybrid FAISS + BM25. The first search after starting takes about 2 s |
  391. | **BigQuery Patent Search** | 1-3 sec | 100M+ patents |
  392. | **USPTO API** | 500ms - 2s | Rate-limited by USPTO |
  393. | **Index Build (NVIDIA GPU)** | 3-5 min | CUDA 12.8 |
  394. | **Index Build (CPU, including Apple Silicon)** | 25-40 min | Measured 37 min on an Apple Silicon Mac; full setup took 38 min |
  395. Resource usage: the loaded search index takes about 2-4GB of RAM and the index files are 500MB-1GB on disk. If you have a GPU, it'll use 1-2GB of VRAM for acceleration.
  396. ---
  397. ## Known Issues
  398. > **This project is a work in progress.** Most features work, but expect some rough edges. Contributions, issues, and PRs are welcome.
  399. Things to be aware of:
  400. - **NVIDIA users: PyTorch install order matters.** Setup handles it. On a hand-made install, install the CUDA build of PyTorch before `sentence-transformers`, or you get the CPU-only build.
  401. - **Patent search needs one setup step.** A free SerpApi key (Quick Start, Step 3), EPO OPS key and secret, or a Google Cloud project for BigQuery. USPTO ODP supplements these providers.
  402. - **Diagrams need Graphviz**, a free program outside Python. Setup offers to install it.
  403. - **The claims check skips the antecedent-basis check by default** (terms like "the controller" used before "a controller"). Its pattern matcher flags too many correct claims. Every claims report names this skipped check; turn it on with `patent-creator config set PATENT_ENABLE_ANTECEDENT_CHECK 1` and review its findings by hand.
  404. - **Windows users need Git Bash** for Claude Code's `claude mcp add`. See [Windows setup notes](#configuration).
  405. - **Claude Code 2.1.280 handshake error `-32022`:** see the [optional stdio workaround](CLAUDE.md#claude-code-handshake-error--32022) for the reported client negotiation bug. Reported by [DanielTillett](https://github.com/RobThePCGuy/Claude-Patent-Creator/issues/102).
  406. See [CLAUDE.md](CLAUDE.md) for the full troubleshooting guide.
  407. ---
  408. ## Glossary
  409. If you're coming from the development side and patent terminology is new (or vice versa), here's a quick reference:
  410. | Term | What it means |
  411. |---|---|
  412. | **MPEP** | Manual of Patent Examining Procedure. The handbook patent examiners use at the USPTO. Think of it as the rulebook. |
  413. | **35 USC** | Title 35 of the United States Code. The federal patent statutes. |
  414. | **37 CFR** | Title 37 of the Code of Federal Regulations. The rules that implement the patent statutes. |
  415. | **USPTO** | United States Patent and Trademark Office. The agency that grants patents. |
  416. | **CPC** | Cooperative Patent Classification. A system for categorizing patents by technology area. |
  417. | **Prior Art** | Anything publicly available before your filing date that's relevant to your invention. Finding it is how you figure out if your idea is actually new. |
  418. | **112(a)** | The section of patent law requiring your application to fully describe and enable the invention. |
  419. | **112(b)** | The section requiring your claims to be definite and clear. |
  420. | **MPEP 608** | The section covering formalities like abstract length, title format, and drawing requirements. |
  421. | **RAG** | Retrieval Augmented Generation. Instead of relying only on what the AI was trained on, it searches a database first and uses those results to give a better answer. |
  422. | **FAISS** | Facebook AI Similarity Search. A fast way to find similar text by comparing mathematical representations of meaning. |
  423. | **BM25** | A text search algorithm that matches exact words and phrases. Works alongside FAISS to catch things vector search might miss. |
  424. | **MCP** | Model Context Protocol. A standard for connecting AI tools to AI models. It's how this system talks to Claude. |
  425. | **MCP server** | The part of this tool that runs quietly in the background and answers Claude's requests. Claude Code starts it for you. |
  426. | **Plugin** | An add-on for Claude Code. This one adds the guided workflows and slash commands. |
  427. | **Terminal** | The window where you type commands: Terminal on a Mac, PowerShell on Windows. |
  428. | **Python** | The programming language this tool is written in. You install it once; you never write any. |
  429. | **Virtual environment (venv)** | A private folder holding this tool and its libraries, so it can't disturb other programs. The Quick Start makes one called `patent-creator-venv`. |
  430. | **pip** | Python's installer. It downloads the tool and its libraries into the virtual environment. |
  431. | **git** | A program for downloading code. pip uses it to fetch this tool from GitHub. |
  432. | **API key** | A password-like code a service gives you so the tool can use it on your behalf. Keep it private. |
  433. | **Homebrew** | The common installer for extra programs on a Mac (`brew install ...`). |
  434. | **IDS** | Information Disclosure Statement. A form listing prior art references you need to disclose to the USPTO. |
  435. ---
  436. ## Roadmap
  437. - [x] Support for international patent offices (EPO, WIPO/PCT)
  438. - [ ] Web interface for non-Claude Code users
  439. - [ ] Claim dependency graph visualization
  440. - [ ] Automated obviousness analysis (35 USC 103)
  441. - [ ] Patent portfolio analysis tools
  442. - [ ] Integration with patent drafting software
  443. ---
  444. ## Contributing
  445. This project is open to contributions. Since it's a work in progress, expect breaking changes and incomplete documentation. Issues and PRs are welcome.
  446. See [CONTRIBUTING.md](CONTRIBUTING.md) for the development setup, branch naming, commit conventions, and code style guide.
  447. ---
  448. ## Credits
  449. ### Open Source Dependencies
  450. This project builds on excellent open source work: [MCP Python SDK](https://github.com/modelcontextprotocol/python-sdk), [FAISS](https://github.com/facebookresearch/faiss) (Meta AI Research), [Sentence Transformers](https://www.sbert.net/) (UKP Lab), [HuggingFace Transformers](https://huggingface.co/transformers/), [PyTorch](https://pytorch.org/), [rank-bm25](https://github.com/dorianbrown/rank_bm25), [PyMuPDF](https://pymupdf.readthedocs.io/), [Graphviz](https://graphviz.org/), [Pydantic](https://docs.pydantic.dev/), and [Google Cloud BigQuery](https://cloud.google.com/bigquery).
  451. ### Data Sources
  452. MPEP, 35 USC, and 37 CFR are published by the USPTO. Patent data comes from Google Patents (through [SerpApi](https://serpapi.com)), EPO OPS and Google BigQuery's `patents-public-data` dataset (100M+ patents), with USPTO ODP application metadata as a supplement. Paper search uses [OpenAlex](https://openalex.org), [arXiv](https://arxiv.org) and [Semantic Scholar](https://www.semanticscholar.org), with dates checked against [Crossref](https://www.crossref.org). Embedding models are [BGE-base-en-v1.5](https://huggingface.co/BAAI/bge-base-en-v1.5) (BAAI) and [MS-MARCO MiniLM-L-6-v2](https://huggingface.co/cross-encoder/ms-marco-MiniLM-L-6-v2) (Microsoft).
  453. ### Trademark Notice
  454. "USPTO" is a registered trademark of the United States Patent and Trademark Office. This project isn't affiliated with, endorsed by, or sponsored by the USPTO.
  455. ---
  456. ## Project Status
  457. This project is in **beta**. I'm actively working on it, but not everything is polished and some features may not work as described. If you run into issues, [open one on GitHub](https://github.com/RobThePCGuy/Claude-Patent-Creator/issues) and I'll take a look.
  458. For detailed documentation: [CLAUDE.md](CLAUDE.md) | For security issues: [SECURITY.md](SECURITY.md)
  459. ---
  460. ## License
  461. MIT License. See [LICENSE](LICENSE) for details.
  462. ---
  463. **Built with Claude Code.** The code is the output, but the real work is deciding what needs to exist and how the pieces fit together.
mcp_server/cli.py · Bundled script · 1,700 lines · 1 finding marked
  1. #!/usr/bin/env python3
  2. """
  3. Command-line interface for Claude Patent Creator
  4. Provides easy setup and management commands
  5. """
  6. import argparse
  7. import json
  8. try:
  9. from cli_command import render as _render_cmd
  10. except ImportError:
  11. try:
  12. from mcp_server.cli_command import render as _render_cmd
  13. except ImportError: # pragma: no cover - keep messages even if the helper is missing
  14. def _render_cmd(message: str) -> str:
  15. return message
  16. import os
  17. import platform
  18. import shutil
  19. import subprocess
  20. import sys
  21. from pathlib import Path
  22. # Ensure bare inter-module imports work when run via the `patent-creator`
  23. # entry point (mcp_server.cli:main). Python only auto-adds the script's
  24. # directory to sys.path for direct execution, not for package entry points.
  25. # See: https://github.com/RobThePCGuy/Claude-Patent-Creator/issues/2
  26. _pkg_dir = str(Path(__file__).parent)
  27. if _pkg_dir not in sys.path:
  28. sys.path.insert(0, _pkg_dir)
  29. # Saved settings must reach the environment before anything reads it: data
  30. # paths (PATENT_DATA_DIR) are computed at import and commands like
  31. # check-bigquery read GOOGLE_CLOUD_PROJECT from the environment. Precedence
  32. # matches the server: real env var > project .env > saved settings.
  33. try:
  34. from dotenv import load_dotenv
  35. # Same files, same order as server.py: the project root .env, then the
  36. # legacy mcp_server/.env. Otherwise setup and the server could disagree on
  37. # settings such as PATENT_DATA_DIR.
  38. for _env_path in (Path(__file__).parent.parent / ".env", Path(__file__).parent / ".env"):
  39. load_dotenv(_env_path, override=False)
  40. except ImportError:
  41. pass
  42. try:
  43. from config import apply_config_to_env as _apply_saved_settings
  44. _apply_saved_settings()
  45. except Exception as _e: # a broken config file must not block 'config' itself
  46. print(f"[WARN] saved settings not applied: {_e}", file=sys.stderr)
  47. # People read this command's output, so prefer readable log lines here. This
  48. # changes only the default; it never touches PATENT_LOG_FORMAT, so the saved
  49. # server setting is reported and inherited unchanged.
  50. try:
  51. from logging_config import prefer_format as _prefer_log_format
  52. _prefer_log_format("human")
  53. except ImportError:
  54. pass
  55. # Import hardware detection for PyTorch installation
  56. import contextlib
  57. import io
  58. # The server stack (mcp, torch, faiss, ...) is heavy and may be unavailable when
  59. # the environment isn't set up yet. Guard these imports so lightweight commands
  60. # such as `config` still run — that is exactly when a user needs to edit settings.
  61. # Heavy commands are gated centrally in main() when the stack failed to load.
  62. # stderr is captured during the attempt so a failed import's diagnostics don't
  63. # leak onto otherwise-clean lightweight commands; real warnings are re-emitted
  64. # on success.
  65. # PyTorch prints this on every Mac import. It is about a distributed-training
  66. # feature this tool never uses, and to a first-time user it reads like an error.
  67. _BENIGN_IMPORT_NOISE = ("Redirects are currently not supported in MacOs",)
  68. def _drop_benign_import_noise(text: str) -> str:
  69. return "".join(
  70. line
  71. for line in text.splitlines(keepends=True)
  72. if not any(noise in line for noise in _BENIGN_IMPORT_NOISE)
  73. )
  74. _server_import_stderr = io.StringIO()
  75. try:
  76. with contextlib.redirect_stderr(_server_import_stderr):
  77. from hardware_detect import (
  78. check_pytorch_installation,
  79. get_pytorch_install_command,
  80. )
  81. from server import (
  82. INDEX_DIR,
  83. MPEP_DIR,
  84. MPEP_DOWNLOAD_URL,
  85. MPEPIndex,
  86. check_all_sources,
  87. check_mpep_pdfs,
  88. download_35_usc,
  89. download_37_cfr,
  90. download_mpep_pdfs,
  91. download_subsequent_publications,
  92. extract_mpep_pdfs,
  93. )
  94. _SERVER_IMPORT_ERROR = None
  95. _SERVER_IMPORT_STDERR = ""
  96. sys.stderr.write(_drop_benign_import_noise(_server_import_stderr.getvalue()))
  97. except (ImportError, SystemExit) as exc: # SystemExit: server.py exits if mcp is missing
  98. _SERVER_IMPORT_ERROR = exc
  99. # Keep the captured diagnostic (e.g. "mcp package not found") to show only if
  100. # a command that actually needs the stack is run — see the guard in main().
  101. # str(SystemExit(1)) is just "1", so this captured text is the real message.
  102. _SERVER_IMPORT_STDERR = _server_import_stderr.getvalue()
  103. check_pytorch_installation = get_pytorch_install_command = None
  104. INDEX_DIR = MPEP_DIR = MPEP_DOWNLOAD_URL = MPEPIndex = None
  105. check_all_sources = check_mpep_pdfs = None
  106. download_35_usc = download_37_cfr = download_mpep_pdfs = None
  107. download_subsequent_publications = extract_mpep_pdfs = None
  108. # EPO/PCT law corpus downloaders (lightweight: requests only). Guarded the
  109. # same way so `patent-creator --help` works in a bare environment.
  110. try:
  111. from epo_downloaders import (
  112. check_epo_pct_sources,
  113. download_epc,
  114. download_pct_guidelines,
  115. download_pct_rules,
  116. download_pct_treaty,
  117. scrape_epo_guidelines,
  118. )
  119. except ImportError:
  120. check_epo_pct_sources = download_epc = None
  121. download_pct_guidelines = download_pct_rules = download_pct_treaty = None
  122. scrape_epo_guidelines = None
  123. # Import path utilities for cross-platform path handling
  124. try:
  125. from path_utils import PathFormatter
  126. except ImportError:
  127. try:
  128. from path_utils import PathFormatter
  129. except ImportError:
  130. PathFormatter = None
  131. def _render(message: str) -> str:
  132. from cli_command import render
  133. return render(message)
  134. def _cli() -> str:
  135. """The exact patent-creator command for this install (see cli_command)."""
  136. from cli_command import installed_cli
  137. return installed_cli()
  138. def install_pytorch():
  139. """Install PyTorch with hardware-specific acceleration.
  140. Returns:
  141. bool: True if PyTorch was reinstalled (caller should restart), False otherwise
  142. """
  143. # Skip if we're in a restarted subprocess (PyTorch already handled)
  144. if os.environ.get("_PYTORCH_ALREADY_INSTALLED"):
  145. return False
  146. # Check current PyTorch status
  147. status = check_pytorch_installation()
  148. if status["installed"]:
  149. print(f" [OK] PyTorch {status['version']} already installed", file=sys.stderr)
  150. # Check if hardware matches
  151. if not status["hardware_match"]:
  152. print(f" [WARNING] {status.get('warning', 'Hardware mismatch')}", file=sys.stderr)
  153. print(" Reinstalling PyTorch with correct hardware support...", file=sys.stderr)
  154. # Don't return - fall through to reinstall
  155. else:
  156. # Already installed and matches hardware
  157. if status.get("cuda_available"):
  158. print(" [OK] CUDA support available", file=sys.stderr)
  159. elif status.get("mps_available"):
  160. print(" [OK] MPS (Apple Silicon) support available", file=sys.stderr)
  161. return False # No reinstall needed
  162. # Get correct PyTorch install command for hardware
  163. package_spec, index_url, description = get_pytorch_install_command()
  164. print(f"\n {description}", file=sys.stderr)
  165. # Uninstall existing PyTorch first (pip won't replace CPU with CUDA automatically)
  166. try:
  167. print(" Uninstalling old PyTorch...", file=sys.stderr)
  168. subprocess.run(
  169. [sys.executable, "-m", "pip", "uninstall", "-y", "torch", "torchvision", "torchaudio"],
  170. check=False, # Don't fail if not installed
  171. capture_output=True,
  172. )
  173. except Exception:
  174. pass # Ignore errors
  175. # Build pip install command. package_spec may contain multiple
  176. # whitespace-separated requirements (e.g. pinned torch + torchvision for
  177. # legacy GPUs), so split it into individual pip arguments.
  178. cmd = [sys.executable, "-m", "pip", "install", *package_spec.split()]
  179. if index_url:
  180. cmd.extend(["--index-url", index_url])
  181. # Install PyTorch
  182. try:
  183. print(" Installing PyTorch...", file=sys.stderr)
  184. subprocess.run(cmd, check=True, capture_output=True, text=True)
  185. print(" [OK] PyTorch installed successfully", file=sys.stderr)
  186. return True # Reinstalled - need to restart Python
  187. except subprocess.CalledProcessError as e:
  188. print(f" [ERROR] PyTorch installation failed: {e}", file=sys.stderr)
  189. print(f" Output: {e.stderr}", file=sys.stderr)
  190. print(" Trying CPU version as fallback...", file=sys.stderr)
  191. # Try CPU version as fallback
  192. try:
  193. subprocess.run([sys.executable, "-m", "pip", "install", "torch>=2.0.0"], check=True)
  194. print(" [OK] PyTorch CPU version installed", file=sys.stderr)
  195. return True # Reinstalled - need to restart Python
  196. except subprocess.CalledProcessError:
  197. print(" [ERROR] Could not install PyTorch. Please install manually:", file=sys.stderr)
  198. print(_render_cmd(' pip install "torch>=2.0.0"'), file=sys.stderr)
  199. return False # Failed, continue anyway
  200. def _auto_detect_bigquery():
  201. """Auto-detect BigQuery credentials and project ID from existing gcloud config.
  202. Checks (in order):
  203. 1. Existing application-default credentials file
  204. 2. GOOGLE_CLOUD_PROJECT env var
  205. 3. gcloud config for default project
  206. 4. Credentials file for quota_project_id
  207. If gcloud is installed and authenticated but no project is set,
  208. attempts to extract it from the credentials file.
  209. """
  210. creds_path = get_gcloud_credentials_path()
  211. # Check existing credentials
  212. if creds_path.exists():
  213. print("\n[OK] BigQuery credentials found", file=sys.stderr)
  214. # Try to extract project ID from credentials if not set in env
  215. if not os.environ.get("GOOGLE_CLOUD_PROJECT"):
  216. try:
  217. import json as _json
  218. with creds_path.open() as f:
  219. creds = _json.load(f)
  220. project_id = creds.get("quota_project_id")
  221. if project_id:
  222. print(f" Auto-detected project: {project_id}", file=sys.stderr)
  223. except Exception:
  224. pass
  225. # Also try gcloud config
  226. if not os.environ.get("GOOGLE_CLOUD_PROJECT"):
  227. try:
  228. result = subprocess.run(
  229. ["gcloud", "config", "get-value", "project"],
  230. capture_output=True, text=True, timeout=5,
  231. )
  232. if result.returncode == 0 and result.stdout.strip() and result.stdout.strip() != "(unset)":
  233. print(f" Auto-detected project: {result.stdout.strip()}", file=sys.stderr)
  234. except Exception:
  235. pass
  236. return
  237. # No credentials — check if gcloud is installed
  238. gcloud_installed = False
  239. try:
  240. result = subprocess.run(
  241. ["gcloud", "--version"], capture_output=True, text=True, timeout=5,
  242. )
  243. gcloud_installed = result.returncode == 0
  244. except Exception:
  245. pass
  246. if gcloud_installed:
  247. # gcloud exists but no application-default credentials
  248. # Try to run auth non-interactively (will fail, but the error is clear)
  249. print("\n[INFO] gcloud CLI detected but no application-default credentials", file=sys.stderr)
  250. print(" To enable BigQuery patent search (100M+ patents, free):", file=sys.stderr)
  251. print(" In a terminal, run: gcloud auth application-default login", file=sys.stderr)
  252. print(" (inside Claude Code you can type: ! gcloud auth application-default login)", file=sys.stderr)
  253. else:
  254. # No gcloud at all — this is fine, BigQuery is optional
  255. print("\n[INFO] BigQuery patent search not configured (optional)", file=sys.stderr)
  256. print(" MPEP search, claims review, and all other features work without it.", file=sys.stderr)
  257. def _verify_bigquery_setup():
  258. """Verify BigQuery is functional — catches missing project ID early during setup."""
  259. try:
  260. from bigquery_search import BigQueryPatentSearch
  261. searcher = BigQueryPatentSearch()
  262. # Quick test query to verify end-to-end
  263. searcher.client.query("SELECT 1", job_config=searcher._make_job_config([])).result(
  264. timeout=10
  265. )
  266. print(
  267. f" BigQuery: [OK] (project: {searcher.billing_project})",
  268. file=sys.stderr,
  269. )
  270. except ValueError:
  271. # Missing project ID or bad config — not a failure, BigQuery is optional
  272. pass
  273. except ImportError:
  274. pass
  275. except Exception:
  276. pass
  277. def mcp_handshake(python_cmd: str, server_script: str, timeout: float = 180.0) -> tuple[bool, str]:
  278. """Start the server exactly as Claude Code will and complete an MCP handshake.
  279. A matching path in ~/.claude.json proves nothing: the registered Python can
  280. exist and still be unable to import mcp. Only a real initialize round trip
  281. shows Claude will connect. Returns (ok, detail) where detail is the server
  282. name on success or the tail of its stderr on failure.
  283. """
  284. import tempfile
  285. import threading
  286. request = {
  287. "jsonrpc": "2.0",
  288. "id": 1,
  289. "method": "initialize",
  290. "params": {
  291. "protocolVersion": "2025-06-18",
  292. "capabilities": {},
  293. "clientInfo": {"name": "patent-creator-verify", "version": "1"},
  294. },
  295. }
  296. err_file = tempfile.TemporaryFile(mode="w+", encoding="utf-8", errors="replace") # noqa: SIM115 - closed on every path below
  297. try:
  298. proc = subprocess.Popen(
  299. [python_cmd, server_script],
  300. stdin=subprocess.PIPE,
  301. stdout=subprocess.PIPE,
  302. stderr=err_file,
  303. text=True,
  304. encoding="utf-8",
  305. errors="replace",
  306. )
  307. except OSError as e:
  308. err_file.close()
  309. return False, f"could not start {python_cmd}: {e}"
  310. found: dict = {}
  311. def _read():
  312. assert proc.stdout is not None
  313. for line in proc.stdout:
  314. try:
  315. msg = json.loads(line)
  316. except ValueError:
  317. continue
  318. if isinstance(msg, dict) and msg.get("id") == 1:
  319. found["msg"] = msg
  320. return
  321. reader = threading.Thread(target=_read, daemon=True)
  322. reader.start()
  323. try:
  324. assert proc.stdin is not None
  325. proc.stdin.write(json.dumps(request) + "\n")
  326. proc.stdin.flush()
  327. except (BrokenPipeError, OSError):
  328. pass
  329. reader.join(timeout)
  330. with contextlib.suppress(Exception):
  331. proc.kill()
  332. with contextlib.suppress(Exception):
  333. proc.wait(timeout=10)
  334. msg = found.get("msg")
  335. err_file.seek(0)
  336. tail = "\n".join(err_file.read().strip().splitlines()[-8:])
  337. err_file.close()
  338. if msg and "result" in msg:
  339. name = ((msg["result"] or {}).get("serverInfo") or {}).get("name", "server")
  340. return True, str(name)
  341. if msg and "error" in msg:
  342. return False, f"server answered with an error: {msg['error']}\n{tail}"
  343. if proc.returncode not in (None, 0, -9) and not reader.is_alive():
  344. return False, tail or f"server exited with code {proc.returncode}"
  345. return False, tail or f"no answer within {int(timeout)} s"
  346. def _report_handshake(python_str: str, server_str: str) -> bool:
  347. print("\nTesting the connection the way Claude Code will...", file=sys.stderr)
  348. ok, detail = mcp_handshake(python_str, server_str)
  349. if ok:
  350. print(f" [OK] Server started and answered ({detail})", file=sys.stderr)
  351. return True
  352. print(" [X] Claude Code will NOT be able to connect: the server did not answer.", file=sys.stderr)
  353. for line in detail.splitlines():
  354. print(f" {line}", file=sys.stderr)
  355. return False
  356. def configure_mcp_server():
  357. """
  358. Register the MCP server with Claude Code using 'claude mcp add' command
  359. """
  360. import platform
  361. # Get correct paths - server.py is in project_root/mcp_server/, not in MPEP_DIR (pdfs/)
  362. project_root = Path(__file__).parent.parent.resolve() # Go up from mcp_server/ to project root
  363. server_script = (project_root / "mcp_server" / "server.py").resolve()
  364. # Keep the venv symlink: resolving it registers the base interpreter,
  365. # which cannot import mcp and makes Claude fail to connect.
  366. python_path = Path(sys.executable).absolute()
  367. print("\n" + "=" * 60, file=sys.stderr)
  368. print("Registering MCP Server with Claude Code", file=sys.stderr)
  369. print("=" * 60, file=sys.stderr)
  370. # Verify paths exist
  371. if not python_path.exists():
  372. print(f"\n[X] Python executable not found: {python_path}", file=sys.stderr)
  373. return False
  374. if not server_script.exists():
  375. print(f"\n[X] Server script not found: {server_script}", file=sys.stderr)
  376. return False
  377. # On Windows, Claude CLI requires git-bash - set environment variable
  378. if platform.system() == "Windows":
  379. try:
  380. result = subprocess.run(["where", "bash"], capture_output=True, text=True, timeout=5)
  381. if result.returncode == 0 and result.stdout.strip():
  382. bash_path = result.stdout.strip().split("\n")[0]
  383. os.environ["CLAUDE_CODE_GIT_BASH_PATH"] = bash_path
  384. except Exception:
  385. pass
  386. # Check if claude command exists
  387. try:
  388. result = subprocess.run(
  389. ["claude", "mcp", "list"], capture_output=True, text=True, timeout=10
  390. )
  391. claude_available = result.returncode == 0
  392. except (subprocess.TimeoutExpired, FileNotFoundError):
  393. claude_available = False
  394. if not claude_available:
  395. print("\n[WARNING] Claude CLI not found in PATH", file=sys.stderr)
  396. print("\nPlease manually register the MCP server:", file=sys.stderr)
  397. # Use PathFormatter if available, otherwise fallback to basic POSIX conversion
  398. if PathFormatter:
  399. python_str, server_str = PathFormatter.format_for_claude_mcp(python_path, server_script)
  400. else:
  401. python_str = str(python_path).replace("\\", "/")
  402. server_str = str(server_script).replace("\\", "/")
  403. print(
  404. f'\n claude mcp add --transport stdio claude-patent-creator --scope user -- "{python_str}" "{server_str}"',
  405. file=sys.stderr,
  406. )
  407. return False
  408. # Remove existing registration if present
  409. with contextlib.suppress(Exception):
  410. subprocess.run(
  411. ["claude", "mcp", "remove", "claude-patent-creator"],
  412. capture_output=True,
  413. timeout=10,
  414. )
  415. # Register the MCP server with correct format
  416. # Use PathFormatter for proper cross-platform path handling
  417. if PathFormatter:
  418. python_str, server_str = PathFormatter.format_for_claude_mcp(python_path, server_script)
  419. else:
  420. python_str = str(python_path).replace("\\", "/")
  421. server_str = str(server_script).replace("\\", "/")
  422. try:
  423. cmd = [
  424. "claude",
  425. "mcp",
  426. "add",
  427. "--transport",
  428. "stdio",
  429. "claude-patent-creator",
  430. "--scope",
  431. "user",
  432. "--",
  433. python_str,
  434. server_str,
  435. ]
  436. result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
  437. if result.returncode == 0:
  438. print("\n[OK] MCP server registered with Claude Code", file=sys.stderr)
  439. print(" Name: claude-patent-creator", file=sys.stderr)
  440. print(f" Python: {python_str}", file=sys.stderr)
  441. print(f" Script: {server_str}", file=sys.stderr)
  442. if not _report_handshake(python_str, server_str):
  443. return False
  444. print("\nVerify with: claude mcp list", file=sys.stderr)
  445. print(f"\nVerify paths with: {_cli()} verify-config", file=sys.stderr)
  446. return True
  447. else:
  448. print(f"\n[X] Failed to register MCP server: {result.stderr}", file=sys.stderr)
  449. print("\nManual registration command:", file=sys.stderr)
  450. print(
  451. f' claude mcp add --transport stdio claude-patent-creator --scope user -- "{python_str}" "{server_str}"',
  452. file=sys.stderr,
  453. )
  454. return False
  455. except Exception as e:
  456. print(f"\n[X] Failed to register MCP server: {e}", file=sys.stderr)
  457. print("\nManual registration command:", file=sys.stderr)
  458. # Use PathFormatter for proper path formatting
  459. if PathFormatter:
  460. python_str, server_str = PathFormatter.format_for_claude_mcp(python_path, server_script)
  461. else:
  462. python_str = str(python_path).replace("\\", "/")
  463. server_str = str(server_script).replace("\\", "/")
  464. print(
  465. f' claude mcp add --transport stdio claude-patent-creator --scope user -- "{python_str}" "{server_str}"',
  466. file=sys.stderr,
  467. )
  468. return False
  469. def get_gcloud_credentials_path():
  470. """
  471. Get the correct gcloud application default credentials path for the current OS
  472. Returns:
  473. Path: Platform-specific credentials path
  474. """
  475. if platform.system() == "Windows":
  476. # Windows: %APPDATA%\gcloud\application_default_credentials.json
  477. appdata = os.environ.get("APPDATA")
  478. if appdata:
  479. return Path(appdata) / "gcloud" / "application_default_credentials.json"
  480. else:
  481. return (
  482. Path.home()
  483. / "AppData"
  484. / "Roaming"
  485. / "gcloud"
  486. / "application_default_credentials.json"
  487. )
  488. else:
  489. # Linux/macOS: $HOME/.config/gcloud/application_default_credentials.json
  490. return Path.home() / ".config" / "gcloud" / "application_default_credentials.json"
  491. def setup_bigquery_auth_prompt():
  492. """
  493. Prompt user to setup BigQuery authentication for patent search
  494. """
  495. print("\n" + "=" * 60, file=sys.stderr)
  496. print("BigQuery Patent Search Setup (Optional)", file=sys.stderr)
  497. print("=" * 60, file=sys.stderr)
  498. print("\nBigQuery provides access to 100M+ patents for prior art search.", file=sys.stderr)
  499. print("Setup takes ~5 minutes and requires a free Google Cloud account.", file=sys.stderr)
  500. print("(No credit card required for BigQuery sandbox)\n", file=sys.stderr)
  501. # Check if already authenticated
  502. creds_path = get_gcloud_credentials_path()
  503. if creds_path.exists():
  504. print("[OK] BigQuery authentication already configured", file=sys.stderr)
  505. print(f" Credentials: {creds_path}", file=sys.stderr)
  506. return True
  507. response = input("Setup BigQuery authentication now? (y/N): ").strip().lower()
  508. if response != "y":
  509. print("\n[SKIPPED] BigQuery is optional. To set it up later:", file=sys.stderr)
  510. print(" 1. Install gcloud: https://cloud.google.com/sdk/docs/install", file=sys.stderr)
  511. print(" 2. Run: gcloud auth application-default login", file=sys.stderr)
  512. print(f" 3. Run: {_cli()} config set GOOGLE_CLOUD_PROJECT your-project-id", file=sys.stderr)
  513. print(f" 4. Test: {_cli()} check-bigquery", file=sys.stderr)
  514. return False
  515. print("\n" + "-" * 60, file=sys.stderr)
  516. print("BigQuery Setup Instructions:", file=sys.stderr)
  517. print("-" * 60, file=sys.stderr)
  518. print("\n1. Install Google Cloud SDK for your OS:", file=sys.stderr)
  519. system = platform.system()
  520. if system == "Windows":
  521. print("\n Windows:", file=sys.stderr)
  522. print(
  523. " - Download: https://dl.google.com/dl/cloudsdk/channels/rapid/GoogleCloudSDKInstaller.exe",
    • Dismissed after review: Links to a Windows program from code, which is how droppers fetch their payload
    • Line 606 on GitHub
  524. file=sys.stderr,
  525. )
  526. print(" - Run the installer and follow prompts", file=sys.stderr)
  527. print(" - Restart this terminal after installation", file=sys.stderr)
  528. elif system == "Darwin": # macOS
  529. print("\n macOS:", file=sys.stderr)
  530. print(" Option A: Using Homebrew (recommended)", file=sys.stderr)
  531. print(" brew install --cask google-cloud-sdk", file=sys.stderr)
  532. print("\n Option B: Manual download", file=sys.stderr)
  533. print(" Download: https://cloud.google.com/sdk/docs/install-sdk", file=sys.stderr)
  534. else: # Linux
  535. print("\n Linux:", file=sys.stderr)
  536. print(" curl https://sdk.cloud.google.com | bash", file=sys.stderr)
  537. print(" exec -l $SHELL # Restart shell", file=sys.stderr)
  538. print("\n2. After installing gcloud, run this command:", file=sys.stderr)
  539. print("\n gcloud auth application-default login", file=sys.stderr)
  540. print("\n3. Sign in with your Google account in the browser", file=sys.stderr)
  541. print(" (Creates a free Google Cloud project if you don't have one)", file=sys.stderr)
  542. print("\n4. Re-run this setup after authentication:", file=sys.stderr)
  543. print(f" {_cli()} setup", file=sys.stderr)
  544. print("\n" + "=" * 60, file=sys.stderr)
  545. input("\nPress Enter to continue setup (BigQuery will be skipped for now)...")
  546. return False
  547. def _stdin_is_interactive() -> bool:
  548. """True when stdin can answer input() prompts."""
  549. try:
  550. if sys.stdin is None or not sys.stdin.isatty():
  551. return False
  552. if sys.platform == "win32":
  553. # NUL is a character device, so isatty() is True for it; only a
  554. # real console handle accepts GetConsoleMode.
  555. import ctypes
  556. import msvcrt
  557. handle = msvcrt.get_osfhandle(sys.stdin.fileno())
  558. mode = ctypes.c_uint32()
  559. return bool(ctypes.windll.kernel32.GetConsoleMode(handle, ctypes.byref(mode)))
  560. return True
  561. except Exception:
  562. return False
  563. def _normalize_interactivity(args) -> None:
  564. """Force non-interactive mode when stdin cannot answer prompts.
  565. Without this, setup's input() calls raise EOFError in CI, agent-driven,
  566. or piped contexts (issue #52). An explicit --non-interactive always wins.
  567. """
  568. if not getattr(args, "non_interactive", False) and not _stdin_is_interactive():
  569. args.non_interactive = True
  570. print(
  571. "[INFO] stdin is not a terminal -- running setup non-interactively",
  572. file=sys.stderr,
  573. )
  574. def _graphviz_install_hint() -> str:
  575. """One platform-specific command a beginner can copy."""
  576. system = platform.system()
  577. if system == "Darwin":
  578. return "brew install graphviz"
  579. if system == "Windows":
  580. return "winget install graphviz"
  581. return "sudo apt-get install graphviz (Fedora: sudo dnf install graphviz)"
  582. def _graphviz_ready() -> bool:
  583. return shutil.which("dot") is not None
  584. def _setup_graphviz(ensure_fn=None, consent=None) -> bool:
  585. """Provision system Graphviz so the diagram tools work out of the box.
  586. Installing Graphviz changes the computer outside this tool (Homebrew,
  587. winget, apt), so it only happens after the user says yes. ``consent`` is
  588. a callable asked once before installing; None means "never install, just
  589. say how" (non-interactive runs). Best effort: any failure prints guidance
  590. and returns False without blocking setup. ``ensure_fn`` is injectable for
  591. tests and bypasses the consent step.
  592. """
  593. print("\nChecking Graphviz (diagram tools)...", file=sys.stderr)
  594. if ensure_fn is None:
  595. if _graphviz_ready():
  596. print(" [OK] Graphviz is installed", file=sys.stderr)
  597. return True
  598. hint = _graphviz_install_hint()
  599. if consent is None or not consent(hint):
  600. print(
  601. " [SKIP] Graphviz is not installed. Only the diagram tools need it."
  602. f"\n To add it later, run: {hint}"
  603. "\n then restart Claude Code.",
  604. file=sys.stderr,
  605. )
  606. return False
  607. try:
  608. from graphviz_installer import ensure_graphviz as ensure_fn
  609. except ImportError:
  610. try:
  611. from mcp_server.graphviz_installer import ensure_graphviz as ensure_fn
  612. except ImportError:
  613. print(" [SKIP] graphviz_installer module unavailable", file=sys.stderr)
  614. return False
  615. try:
  616. ready, message = ensure_fn()
  617. except Exception as e: # never let the diagram step break setup
  618. print(f" [WARN] Graphviz install attempt failed: {e}", file=sys.stderr)
  619. print(" Diagram tools will stay disabled until Graphviz is installed.", file=sys.stderr)
  620. return False
  621. tag = "[OK]" if ready else "[WARN]"
  622. print(f" {tag} {message}", file=sys.stderr)
  623. if not ready:
  624. print(" Diagram tools will stay disabled until Graphviz is installed.", file=sys.stderr)
  625. return ready
  626. def _setup_epo_pct_sources(dest_dir) -> bool:
  627. """Download any missing EPO/PCT law sources into dest_dir (issue #49).
  628. Best effort by design: EPO/WIPO being unreachable must never block US
  629. setup — the law-search tools already say honestly when a corpus is
  630. missing (#48). Returns True if at least one new source landed, so the
  631. caller knows the index needs a rebuild to make it searchable.
  632. """
  633. if check_epo_pct_sources is None:
  634. return False
  635. downloaders = {
  636. "epc": ("EPC (European Patent Convention)", download_epc),
  637. "epo_guidelines": ("EPO Guidelines", scrape_epo_guidelines),
  638. "pct_treaty": ("PCT Treaty", download_pct_treaty),
  639. "pct_rules": ("PCT Regulations", download_pct_rules),
  640. "pct_guidelines": ("PCT Guidelines", download_pct_guidelines),
  641. }
  642. try:
  643. status = check_epo_pct_sources(dest_dir)
  644. except Exception as e:
  645. print(f" EPO/PCT source check failed: {e}", file=sys.stderr)
  646. return False
  647. got_new = False
  648. for key, (label, download_fn) in downloaders.items():
  649. if status.get(key):
  650. print(f" {label}: [OK]", file=sys.stderr)
  651. continue
  652. try:
  653. ok = download_fn(dest_dir)
  654. except Exception as e:
  655. print(f" {label}: [X] {e}", file=sys.stderr)
  656. continue
  657. if ok:
  658. got_new = True
  659. print(f" {label}: [OK] downloaded", file=sys.stderr)
  660. else:
  661. print(
  662. f" {label}: [X] download failed (EPO/PCT law search will "
  663. "report the missing corpus honestly)",
  664. file=sys.stderr,
  665. )
  666. return got_new
  667. def setup_command(args):
  668. """
  669. One-command setup: installs PyTorch, downloads all sources, and builds index
  670. """
  671. # Propagate --no-hyde as an env var so downstream modules (health_check,
  672. # mpep_search) can honour it without receiving the argparse namespace.
  673. if args.no_hyde:
  674. os.environ["PATENT_MPEP_USE_HYDE"] = "false"
  675. print("\n" + "=" * 60, file=sys.stderr)
  676. print("Claude Patent Creator - Automatic Setup", file=sys.stderr)
  677. print("=" * 60, file=sys.stderr)
  678. _normalize_interactivity(args)
  679. # Step 1: Install PyTorch with hardware detection
  680. print("\n[1/4] Checking PyTorch installation...", file=sys.stderr)
  681. pytorch_reinstalled = install_pytorch()
  682. # If PyTorch was reinstalled, restart in subprocess with fresh Python interpreter
  683. if pytorch_reinstalled:
  684. print(
  685. "\n [INFO] Restarting setup with fresh Python interpreter to load new PyTorch...\n",
  686. file=sys.stderr,
  687. )
  688. # Re-exec this script in a subprocess to get fresh Python with new PyTorch
  689. result = subprocess.run(
  690. [sys.executable, "-m", "mcp_server.cli", "setup"]
  691. + (["--rebuild"] if args.rebuild else [])
  692. + (["--no-hyde"] if args.no_hyde else [])
  693. + (["--non-interactive"] if getattr(args, "non_interactive", False) else []),
  694. env={**os.environ, "_PYTORCH_ALREADY_INSTALLED": "1"},
  695. )
  696. return result.returncode
  697. # Step 2: Check current status
  698. print("\n[2/4] Checking source files...", file=sys.stderr)
  699. sources_status = check_all_sources()
  700. pdf_count = check_mpep_pdfs()
  701. print("\nChecking current status...", file=sys.stderr)
  702. if sources_status["mpep"]:
  703. print(f" MPEP PDFs: [OK] ({pdf_count} files)", file=sys.stderr)
  704. elif _index_ready():
  705. print(
  706. " MPEP PDFs: [--] removed after indexing (only needed to rebuild the index)",
  707. file=sys.stderr,
  708. )
  709. else:
  710. print(" MPEP PDFs: [X] (0 files)", file=sys.stderr)
  711. print(_source_line("35 USC:", sources_status["35_usc"]), file=sys.stderr)
  712. print(_source_line("37 CFR:", sources_status["37_cfr"]), file=sys.stderr)
  713. print(_source_line("Updates:", sources_status["subsequent_pubs"]), file=sys.stderr)
  714. # PDFs removed after indexing (setup offers this): the index still works,
  715. # so don't re-download ~500 MB and rebuild for half an hour unasked.
  716. # An index built by an older version with a known defect gets rebuilt
  717. # automatically; re-running setup is what a user does to update.
  718. index_defects = _index_defects()
  719. if index_defects and not args.rebuild:
  720. print("\n[!] Your search index needs rebuilding:", file=sys.stderr)
  721. for warning in index_defects:
  722. print(f" {warning}", file=sys.stderr)
  723. print(" Rebuilding it now (sources are downloaded again if needed).", file=sys.stderr)
  724. args.rebuild = True
  725. pdfs_cleaned_up = (
  726. not sources_status["mpep"] and _index_ready() and not getattr(args, "rebuild", False)
  727. )
  728. # Download missing sources
  729. downloads_needed = []
  730. if pdfs_cleaned_up:
  731. print(
  732. "\n[OK] Search index already built; its source PDFs were removed, which is fine."
  733. f"\n Run '{_cli()} setup --rebuild' only if you want to rebuild it.",
  734. file=sys.stderr,
  735. )
  736. else:
  737. if not sources_status["mpep"]:
  738. downloads_needed.append("MPEP")
  739. if not sources_status["35_usc"]:
  740. downloads_needed.append("35 USC")
  741. if not sources_status["37_cfr"]:
  742. downloads_needed.append("37 CFR")
  743. if not sources_status["subsequent_pubs"]:
  744. downloads_needed.append("Subsequent Publications")
  745. if downloads_needed:
  746. print(f"\n[3/4] Downloading: {', '.join(downloads_needed)}", file=sys.stderr)
  747. print("This may take several minutes...\n", file=sys.stderr)
  748. operations = {
  749. "MPEP": lambda: download_mpep_pdfs(MPEP_DOWNLOAD_URL) and extract_mpep_pdfs(),
  750. "35 USC": download_35_usc,
  751. "37 CFR": download_37_cfr,
  752. "Subsequent Publications": download_subsequent_publications,
  753. }
  754. missing_optional = []
  755. for label in downloads_needed:
  756. if operations[label]():
  757. continue
  758. if label == "Subsequent Publications":
  759. # A supplement to the MPEP: search still works without it, and
  760. # the coverage report names it as missing.
  761. print(
  762. f"\n[!] {label} download failed. Continuing without it; "
  763. "searches won't include those updates.",
  764. file=sys.stderr,
  765. )
  766. missing_optional.append(label)
  767. continue
  768. print(f"\n[X] {label} download or extraction failed. Setup stopped.", file=sys.stderr)
  769. return 1
  770. if missing_optional:
  771. print(f"\n[OK] Required downloads complete ({', '.join(missing_optional)} missing)", file=sys.stderr)
  772. else:
  773. print("\n[OK] All downloads complete", file=sys.stderr)
  774. elif not pdfs_cleaned_up:
  775. print("\n[OK] All sources already present", file=sys.stderr)
  776. # EPO/PCT law corpus (issue #49): best effort, never blocks US setup.
  777. print("\nChecking EPO/PCT law sources...", file=sys.stderr)
  778. epo_sources_added = False if pdfs_cleaned_up else _setup_epo_pct_sources(MPEP_DIR)
  779. # Build index. Newly downloaded EPO/PCT sources require a rebuild —
  780. # an existing index knows nothing about them.
  781. index_exists = (INDEX_DIR / "mpep_index.faiss").exists()
  782. if epo_sources_added and index_exists and not args.rebuild:
  783. print(
  784. "\n New EPO/PCT sources downloaded — rebuilding index to include them.",
  785. file=sys.stderr,
  786. )
  787. if args.rebuild or not index_exists or epo_sources_added:
  788. print("\n[4/4] Building search index...", file=sys.stderr)
  789. try:
  790. import torch
  791. on_gpu = torch.cuda.is_available()
  792. except Exception:
  793. on_gpu = False
  794. print(
  795. "This takes about 5 minutes with an NVIDIA GPU"
  796. if on_gpu
  797. else "This takes 25-40 minutes on this computer (it builds on the CPU).",
  798. file=sys.stderr,
  799. )
  800. print("A progress line appears every few percent.\n", file=sys.stderr)
  801. # HyDE only expands search queries; building never uses it.
  802. mpep_index = MPEPIndex(use_hyde=False)
  803. mpep_index.build_index(force_rebuild=True)
  804. print("\n[OK] Index built successfully", file=sys.stderr)
  805. else:
  806. print("\n[OK] Index already exists (use --rebuild to force rebuild)", file=sys.stderr)
  807. # Diagram tools: provision system Graphviz only with the user's yes
  808. # (it installs a system program), best effort, never blocks setup.
  809. def _ask_graphviz(hint: str) -> bool:
  810. answer = input(
  811. "\nThe diagram tools need a free program called Graphviz."
  812. f"\nInstall it now by running '{hint}'? (Y/n): "
  813. )
  814. return answer.strip().lower() in ("", "y", "yes")
  815. _setup_graphviz(consent=None if getattr(args, "non_interactive", False) else _ask_graphviz)
  816. # Setup BigQuery authentication (auto-detect in non-interactive, prompt in interactive)
  817. if not getattr(args, "non_interactive", False):
  818. setup_bigquery_auth_prompt()
  819. else:
  820. # Non-interactive: auto-detect existing gcloud auth + project ID
  821. _auto_detect_bigquery()
  822. # Verify BigQuery actually works (catches missing project ID)
  823. _verify_bigquery_setup()
  824. # Configure MCP server
  825. mcp_configured = configure_mcp_server()
  826. # Final status
  827. print("\n" + "=" * 60, file=sys.stderr)
  828. print(
  829. "Setup Complete!" if mcp_configured else "Setup finished, but Claude Code is NOT connected yet",
  830. file=sys.stderr,
  831. )
  832. print("=" * 60, file=sys.stderr)
  833. sources_status = check_all_sources()
  834. index_exists = (INDEX_DIR / "mpep_index.faiss").exists()
  835. print("\nFinal status:", file=sys.stderr)
  836. final_pdfs = check_mpep_pdfs()
  837. print(
  838. f" MPEP PDFs: [OK] ({final_pdfs} files)"
  839. if final_pdfs
  840. else " MPEP PDFs: [--] removed after indexing (only needed to rebuild the index)",
  841. file=sys.stderr,
  842. )
  843. print(_source_line("35 USC:", sources_status["35_usc"]), file=sys.stderr)
  844. print(_source_line("37 CFR:", sources_status["37_cfr"]), file=sys.stderr)
  845. print(_source_line("Updates:", sources_status["subsequent_pubs"]), file=sys.stderr)
  846. print(" Index: [OK]" if index_exists else " Index: [X]", file=sys.stderr)
  847. print(
  848. f" MCP: {'[OK]' if mcp_configured else '[WARNING] Manual setup required'}",
  849. file=sys.stderr,
  850. )
  851. if mcp_configured:
  852. print("\nClaude Code Integration:", file=sys.stderr)
  853. print(" [OK] MCP server registered (user scope)", file=sys.stderr)
  854. print(" [OK] Available from any directory", file=sys.stderr)
  855. else:
  856. print("\n[WARNING] MCP server auto-registration failed", file=sys.stderr)
  857. print(" See manual registration command above", file=sys.stderr)
  858. # The skills (incl. the patent-application-creator campaign workflow)
  859. # ship as a Claude Code plugin, NOT inside this Python package — without
  860. # these two commands a user gets the tools but never the campaign.
  861. print("\nClaude Code skills (patent campaign workflow):", file=sys.stderr)
  862. print(
  863. " claude plugin marketplace add RobThePCGuy/Claude-Patent-Creator",
  864. file=sys.stderr,
  865. )
  866. print(
  867. " claude plugin install claude-patent-creator-standalone@claude-patent-creator",
  868. file=sys.stderr,
  869. )
  870. print(
  871. " (re-run the install command after upgrades to refresh the skills)",
  872. file=sys.stderr,
  873. )
  874. # Check BigQuery status for final message
  875. bq_works = False
  876. try:
  877. from bigquery_search import BigQueryPatentSearch
  878. # Construct to verify BigQuery is reachable/configured; raises if not.
  879. BigQueryPatentSearch()
  880. bq_works = True
  881. except Exception:
  882. pass
  883. if not mcp_configured:
  884. print(
  885. f"\nFix the connection problem shown above, then run '{_cli()} setup' again."
  886. "\n(The download and index are kept, so it finishes in under a minute.)",
  887. file=sys.stderr,
  888. )
  889. return 1
  890. print("\nReady to use! Restart Claude Code, then try:", file=sys.stderr)
  891. print(' "Search MPEP for claim definiteness requirements"', file=sys.stderr)
  892. print(' "Review my patent claims for 35 USC 112(b) compliance"', file=sys.stderr)
  893. if bq_works:
  894. print(' "Search for patents about neural networks filed in 2024"', file=sys.stderr)
  895. return 0
  896. def _index_ready() -> bool:
  897. """The search index is what the server runs on; the PDFs are only needed to
  898. rebuild it. Setup offers to delete them after indexing, so readiness must
  899. never depend on them."""
  900. return (INDEX_DIR / "mpep_index.faiss").exists() and (
  901. INDEX_DIR / "mpep_metadata.json"
  902. ).exists()
  903. _INDEXED_SOURCES: "set[str] | None" = None
  904. def _indexed_sources() -> set[str]:
  905. """Source types present in the built index's metadata (cached)."""
  906. global _INDEXED_SOURCES
  907. if _INDEXED_SOURCES is None:
  908. try:
  909. with (INDEX_DIR / "mpep_metadata.json").open(encoding="utf-8") as f:
  910. _INDEXED_SOURCES = {m.get("source", "MPEP") for m in json.load(f).get("metadata", [])}
  911. except Exception:
  912. _INDEXED_SOURCES = set()
  913. return _INDEXED_SOURCES
  914. # Status label -> source type the extractor records in index metadata.
  915. _LABEL_SOURCE = {"35 USC:": "35_USC", "37 CFR:": "37_CFR", "Updates:": "SUBSEQUENT"}
  916. def _source_line(label: str, present: bool) -> str:
  917. """One status line for a downloaded source file. A removed file is fine
  918. only when the index really holds that source's text; otherwise it is
  919. missing and flagged."""
  920. if present:
  921. mark = "[OK]"
  922. elif _index_ready() and _LABEL_SOURCE.get(label) in _indexed_sources():
  923. mark = "[--] removed after indexing (its text is in the search index)"
  924. else:
  925. mark = "[X]"
  926. return f" {label:<10} {mark}"
  927. def _index_defects() -> list[str]:
  928. """Known defects in an already-built index that only a rebuild fixes
  929. (e.g. indexes built before the EPC article/rule split was repaired)."""
  930. if not _index_ready():
  931. return []
  932. try:
  933. from mpep_search import get_index_warnings
  934. with (INDEX_DIR / "mpep_metadata.json").open(encoding="utf-8") as f:
  935. metadata = json.load(f).get("metadata", [])
  936. return [_render(w) for w in get_index_warnings(metadata)]
  937. except Exception:
  938. return []
  939. def run_server(args):
  940. """
  941. Run the MCP server
  942. """
  943. # Check if setup has been run
  944. if not _index_ready():
  945. print(
  946. f"\n[X] Setup not complete. Run '{_cli()} setup' first.",
  947. file=sys.stderr,
  948. )
  949. return 1
  950. print("Starting MCP server...", file=sys.stderr)
  951. # Run the server.py script as a subprocess to ensure clean initialization
  952. # and proper tool registration exactly like 'claude mcp add' does
  953. server_script = Path(__file__).parent / "server.py"
  954. cmd = [sys.executable, str(server_script)]
  955. # Bridge file-backed settings into the environment so the server subprocess
  956. # inherits them (an explicitly-set env var still wins). See mcp_server.config.
  957. from config import apply_config_to_env
  958. apply_config_to_env()
  959. env = os.environ.copy()
  960. if args.no_hyde:
  961. env["PATENT_MPEP_USE_HYDE"] = "false"
  962. try:
  963. result = subprocess.run(cmd, env=env)
  964. return result.returncode
  965. except KeyboardInterrupt:
  966. return 0
  967. def status_command(args):
  968. """
  969. Show current installation status
  970. """
  971. sources_status = check_all_sources()
  972. pdf_count = check_mpep_pdfs()
  973. index_exists = (INDEX_DIR / "mpep_index.faiss").exists()
  974. print("\nClaude Patent Creator Status", file=sys.stderr)
  975. print("=" * 40, file=sys.stderr)
  976. # GPU Status
  977. import torch
  978. print("\nHardware:", file=sys.stderr)
  979. if torch.cuda.is_available():
  980. gpu_name = torch.cuda.get_device_name(0)
  981. gpu_memory = torch.cuda.get_device_properties(0).total_memory / 1024**3
  982. print(f" GPU: [OK] {gpu_name}", file=sys.stderr)
  983. print(f" Memory: {gpu_memory:.1f} GB", file=sys.stderr)
  984. else:
  985. print(" GPU: [X] Not available (using CPU)", file=sys.stderr)
  986. print("\nSources:", file=sys.stderr)
  987. if sources_status["mpep"]:
  988. print(f" MPEP PDFs: [OK] ({pdf_count} files)", file=sys.stderr)
  989. elif _index_ready():
  990. print(
  991. " MPEP PDFs: [--] removed after indexing (only needed to rebuild the index)",
  992. file=sys.stderr,
  993. )
  994. else:
  995. print(" MPEP PDFs: [X] (0 files)", file=sys.stderr)
  996. print(_source_line("35 USC:", sources_status["35_usc"]), file=sys.stderr)
  997. print(_source_line("37 CFR:", sources_status["37_cfr"]), file=sys.stderr)
  998. print(_source_line("Updates:", sources_status["subsequent_pubs"]), file=sys.stderr)
  999. print("\nIndex:", file=sys.stderr)
  1000. print(f" Built: {'[OK]' if index_exists else '[X]'}", file=sys.stderr)
  1001. if index_exists:
  1002. metadata_file = INDEX_DIR / "mpep_metadata.json"
  1003. if metadata_file.exists():
  1004. import json
  1005. with metadata_file.open(encoding="utf-8") as f:
  1006. data = json.load(f)
  1007. print(f" Chunks: {len(data['chunks']):,}", file=sys.stderr)
  1008. print(
  1009. f" Sections: {len({m['section'] for m in data['metadata']}):,}",
  1010. file=sys.stderr,
  1011. )
  1012. for warning in _index_defects():
  1013. print(f" [!] {warning}", file=sys.stderr)
  1014. print("\nStorage:", file=sys.stderr)
  1015. print(f" Location: {MPEP_DIR.absolute()}", file=sys.stderr)
  1016. print(f" Index dir: {INDEX_DIR.absolute()}", file=sys.stderr)
  1017. ready = _index_ready()
  1018. defects = _index_defects()
  1019. label = "Setup required" if not ready else ("Ready, but the index needs a rebuild" if defects else "Ready")
  1020. print(f"\nStatus: {label}", file=sys.stderr)
  1021. if not ready:
  1022. print(f"\nRun '{_cli()} setup' to complete installation.", file=sys.stderr)
  1023. elif defects:
  1024. print(f"\nRun '{_cli()} setup' to rebuild it (25-40 minutes without an NVIDIA GPU).", file=sys.stderr)
  1025. return 0
  1026. def verify_config_command(args):
  1027. """Verify Claude Code MCP configuration"""
  1028. print("\n" + "=" * 70, file=sys.stderr)
  1029. print("Claude Code MCP Configuration Verification", file=sys.stderr)
  1030. print("=" * 70, file=sys.stderr)
  1031. # Determine config file location
  1032. home_dir = Path.home()
  1033. config_path = home_dir / ".claude.json"
  1034. # Get expected paths
  1035. project_root = Path(__file__).parent.parent.resolve()
  1036. expected_python = Path(sys.executable).absolute()
  1037. expected_server = (project_root / "mcp_server" / "server.py").resolve()
  1038. print("\nExpected Configuration:", file=sys.stderr)
  1039. print(f" Python: {expected_python}", file=sys.stderr)
  1040. print(f" Server: {expected_server}", file=sys.stderr)
  1041. print(f" Config: {config_path}", file=sys.stderr)
  1042. # Check if paths exist
  1043. print("\nPath Verification:", file=sys.stderr)
  1044. if expected_python.exists():
  1045. print(" [OK] Python executable found", file=sys.stderr)
  1046. else:
  1047. print(f" [X] Python executable NOT found: {expected_python}", file=sys.stderr)
  1048. if expected_server.exists():
  1049. print(" [OK] Server script found", file=sys.stderr)
  1050. else:
  1051. print(f" [X] Server script NOT found: {expected_server}", file=sys.stderr)
  1052. # Check Claude config
  1053. print("\nClaude Configuration:", file=sys.stderr)
  1054. if not config_path.exists():
  1055. print(f" [X] Config file not found: {config_path}", file=sys.stderr)
  1056. print(f"\n Run '{_cli()} setup' to create it", file=sys.stderr)
  1057. return 1
  1058. try:
  1059. with config_path.open(encoding="utf-8") as f:
  1060. config = json.load(f)
  1061. if "mcpServers" not in config:
  1062. print(" [X] No 'mcpServers' section found", file=sys.stderr)
  1063. return 1
  1064. if "claude-patent-creator" not in config["mcpServers"]:
  1065. print(" [X] 'claude-patent-creator' server not registered", file=sys.stderr)
  1066. print(f"\n Run: {_cli()} setup", file=sys.stderr)
  1067. return 1
  1068. server_config = config["mcpServers"]["claude-patent-creator"]
  1069. actual_python = server_config.get("command", "")
  1070. actual_args = server_config.get("args", [])
  1071. actual_server = actual_args[0] if actual_args else ""
  1072. print(" [OK] Configuration found", file=sys.stderr)
  1073. print("\nActual Configuration:", file=sys.stderr)
  1074. print(f" Python: {actual_python}", file=sys.stderr)
  1075. print(f" Server: {actual_server}", file=sys.stderr)
  1076. # Normalize paths for comparison (handle forward/backslash differences)
  1077. def normalize_path(p):
  1078. return str(Path(p).resolve()).lower() if p else ""
  1079. def normalize_interpreter(p):
  1080. # Never resolve an interpreter: a venv python and its base
  1081. # interpreter resolve to the same file but behave differently.
  1082. return str(Path(p).absolute()).replace("\\", "/").lower() if p else ""
  1083. expected_python_norm = normalize_interpreter(expected_python)
  1084. expected_server_norm = normalize_path(expected_server)
  1085. actual_python_norm = normalize_interpreter(actual_python)
  1086. actual_server_norm = normalize_path(actual_server)
  1087. print("\nConfiguration Status:", file=sys.stderr)
  1088. python_match = expected_python_norm == actual_python_norm
  1089. server_match = expected_server_norm == actual_server_norm
  1090. if python_match:
  1091. print(" [OK] Python path is correct", file=sys.stderr)
  1092. else:
  1093. print(" [X] Python path mismatch!", file=sys.stderr)
  1094. print(f" Expected: {expected_python}", file=sys.stderr)
  1095. print(f" Actual: {actual_python}", file=sys.stderr)
  1096. if server_match:
  1097. print(" [OK] Server path is correct", file=sys.stderr)
  1098. else:
  1099. print(" [X] Server path mismatch!", file=sys.stderr)
  1100. print(f" Expected: {expected_server}", file=sys.stderr)
  1101. print(f" Actual: {actual_server}", file=sys.stderr)
  1102. if python_match and server_match and not _report_handshake(actual_python, actual_server):
  1103. print(f"\n[X] The registered server does not start. Re-run: {_cli()} setup", file=sys.stderr)
  1104. return 1
  1105. if python_match and server_match:
  1106. print("\n[OK] Configuration is correct!", file=sys.stderr)
  1107. print("\nIf the server still fails:", file=sys.stderr)
  1108. print(" 1. Restart Claude Code", file=sys.stderr)
  1109. print(" 2. Check logs in Claude Code", file=sys.stderr)
  1110. print(" 3. Try: claude mcp list", file=sys.stderr)
  1111. return 0
  1112. else:
  1113. print("\n[X] Configuration needs to be fixed!", file=sys.stderr)
  1114. print("\nTo fix:", file=sys.stderr)
  1115. print(f" Option 1: Run '{_cli()} setup' to re-register", file=sys.stderr)
  1116. print(f" Option 2: Manually edit {config_path}", file=sys.stderr)
  1117. print("\nCorrect values:", file=sys.stderr)
  1118. print(f' "command": "{expected_python.as_posix()}"', file=sys.stderr)
  1119. print(f' "args": ["{expected_server.as_posix()}"]', file=sys.stderr)
  1120. return 1
  1121. except json.JSONDecodeError as e:
  1122. print(f" [X] Invalid JSON in config file: {e}", file=sys.stderr)
  1123. return 1
  1124. except Exception as e:
  1125. print(f" [X] Error reading config: {e}", file=sys.stderr)
  1126. return 1
  1127. def check_bigquery_command(args):
  1128. """
  1129. Check BigQuery authentication and availability
  1130. """
  1131. print("\n" + "=" * 60, file=sys.stderr)
  1132. print("BigQuery Authentication Check", file=sys.stderr)
  1133. print("=" * 60, file=sys.stderr)
  1134. try:
  1135. from bigquery_search import check_bigquery_available
  1136. except ImportError:
  1137. # Fallback if imported from elsewhere
  1138. from mcp_server.bigquery_search import check_bigquery_available
  1139. status = check_bigquery_available()
  1140. if status.get("available"):
  1141. print("\n[OK] BigQuery is successfully authenticated and available!", file=sys.stderr)
  1142. print(f" Project: {status.get('project')}", file=sys.stderr)
  1143. if "us_patents" in status:
  1144. print(f" US Patents Indexed: {status.get('us_patents'):,}", file=sys.stderr)
  1145. return 0
  1146. else:
  1147. print("\n[X] BigQuery is NOT available", file=sys.stderr)
  1148. print(f" Error: {status.get('error', 'Unknown error')}", file=sys.stderr)
  1149. if "message" in status:
  1150. print(f" Details: {status.get('message')}", file=sys.stderr)
  1151. if "install_command" in status:
  1152. print(f"\n To fix run: {status.get('install_command')}", file=sys.stderr)
  1153. return 1
  1154. def health_command(args):
  1155. """Alias for status command"""
  1156. return status_command(args)
  1157. def rebuild_index_command(args):
  1158. """Rebuild MPEP search index"""
  1159. print("\n" + "=" * 60, file=sys.stderr)
  1160. print("Building MPEP Search Index", file=sys.stderr)
  1161. print("=" * 60, file=sys.stderr)
  1162. sources_status = check_all_sources()
  1163. if not sources_status["mpep"]:
  1164. print(f"\n[X] MPEP PDFs not found. Run '{_cli()} download-mpep' or 'setup' first.", file=sys.stderr)
  1165. return 1
  1166. # Propagate env var for use_hyde
  1167. if getattr(args, "no_hyde", False):
  1168. os.environ["PATENT_MPEP_USE_HYDE"] = "false"
  1169. # HyDE only expands search queries; building never uses it.
  1170. mpep_index = MPEPIndex(use_hyde=False)
  1171. mpep_index.build_index(force_rebuild=True)
  1172. print("\n[OK] MPEP index rebuilt successfully", file=sys.stderr)
  1173. return 0
  1174. def download_mpep_command(args):
  1175. """Download MPEP PDFs only"""
  1176. print("\n" + "=" * 60, file=sys.stderr)
  1177. print("Downloading MPEP PDFs", file=sys.stderr)
  1178. print("=" * 60, file=sys.stderr)
  1179. if download_mpep_pdfs(MPEP_DOWNLOAD_URL) and extract_mpep_pdfs():
  1180. print("\n[OK] MPEP download and extraction complete", file=sys.stderr)
  1181. return 0
  1182. else:
  1183. print("\n[X] MPEP download or extraction failed.", file=sys.stderr)
  1184. return 1
  1185. def download_all_command(args):
  1186. """Download all sources (MPEP + 35 USC + 37 CFR)"""
  1187. print("\n" + "=" * 60, file=sys.stderr)
  1188. print("Downloading All USPTO Sources", file=sys.stderr)
  1189. print("=" * 60, file=sys.stderr)
  1190. success = True
  1191. if download_mpep_pdfs(MPEP_DOWNLOAD_URL) and extract_mpep_pdfs():
  1192. print("[OK] MPEP complete", file=sys.stderr)
  1193. else:
  1194. print("[X] MPEP failed", file=sys.stderr)
  1195. success = False
  1196. for label, download in [("35 USC", download_35_usc), ("37 CFR", download_37_cfr),
  1197. ("Updates", download_subsequent_publications)]:
  1198. if download():
  1199. print(f"[OK] {label} complete", file=sys.stderr)
  1200. else:
  1201. print(f"[X] {label} download failed", file=sys.stderr)
  1202. success = False
  1203. print("\nEPO/PCT law sources:", file=sys.stderr)
  1204. if _setup_epo_pct_sources(MPEP_DIR):
  1205. print(
  1206. f" New EPO/PCT sources downloaded. Run '{_cli()} setup --rebuild' "
  1207. "to make them searchable.",
  1208. file=sys.stderr,
  1209. )
  1210. if success:
  1211. print("\n[OK] Required US source downloads completed successfully", file=sys.stderr)
  1212. return 0
  1213. else:
  1214. print("\n[X] Required US source downloads failed. See the errors above.", file=sys.stderr)
  1215. return 1
  1216. def _format_config_value(opt, value, source):
  1217. """Render a setting for display, masking secrets."""
  1218. if opt.is_secret:
  1219. shown = "(set)" if value else "(not set)"
  1220. elif value == "":
  1221. shown = "(empty)"
  1222. else:
  1223. shown = value
  1224. return shown, source
  1225. def config_list_command(args):
  1226. """Print all settings, their effective values, and where each comes from."""
  1227. from config import OPTIONS, config_path, get_effective
  1228. sections: dict = {}
  1229. for opt in OPTIONS:
  1230. sections.setdefault(opt.section, []).append(opt)
  1231. print(f"Config file: {config_path()}\n")
  1232. print("Resolution order: environment variable > config file > default\n")
  1233. for section, opts in sections.items():
  1234. print(f"== {section} ==")
  1235. for opt in opts:
  1236. value, source = get_effective(opt.key)
  1237. shown, _ = _format_config_value(opt, value, source)
  1238. print(f" {opt.key}")
  1239. print(f" = {shown} [{source}]")
  1240. print(f" {opt.description}")
  1241. if opt.note:
  1242. print(f" note: {_render(opt.note)}")
  1243. print()
  1244. print(f"Change a setting: {_cli()} config set <KEY> <VALUE>")
  1245. return 0
  1246. def config_get_command(args):
  1247. from config import OPTIONS_BY_KEY, get_effective
  1248. if args.key not in OPTIONS_BY_KEY:
  1249. print(f"[X] Unknown setting: {args.key}", file=sys.stderr)
  1250. print(f" Run '{_cli()} config list' to see valid keys.", file=sys.stderr)
  1251. return 1
  1252. value, source = get_effective(args.key)
  1253. opt = OPTIONS_BY_KEY[args.key]
  1254. shown, _ = _format_config_value(opt, value, source)
  1255. print(f"{shown} [{source}]")
  1256. return 0
  1257. def config_set_command(args):
  1258. from config import OPTIONS_BY_KEY, normalize, save_value, validate
  1259. if args.key not in OPTIONS_BY_KEY:
  1260. print(f"[X] Unknown setting: {args.key}", file=sys.stderr)
  1261. print(f" Run '{_cli()} config list' to see valid keys.", file=sys.stderr)
  1262. return 1
  1263. error = validate(args.key, args.value)
  1264. if error:
  1265. print(f"[X] Invalid value for {args.key}: {error}", file=sys.stderr)
  1266. return 1
  1267. value = normalize(args.key, args.value)
  1268. path = save_value(args.key, value)
  1269. opt = OPTIONS_BY_KEY[args.key]
  1270. shown = "(set)" if opt.is_secret else value
  1271. print(f"[OK] {args.key} = {shown}")
  1272. print(f" Saved to {path}")
  1273. if opt.is_secret:
  1274. print(" Note: stored in plaintext; protect this file.", file=sys.stderr)
  1275. if opt.note:
  1276. print(f" {_render(opt.note)}")
  1277. return 0
  1278. def config_unset_command(args):
  1279. from config import OPTIONS_BY_KEY, unset_value
  1280. if args.key not in OPTIONS_BY_KEY:
  1281. print(f"[X] Unknown setting: {args.key}", file=sys.stderr)
  1282. return 1
  1283. unset_value(args.key)
  1284. print(f"[OK] {args.key} removed from the config file (default/env now apply).")
  1285. return 0
  1286. def config_path_command(args):
  1287. from config import config_path
  1288. print(config_path())
  1289. return 0
  1290. def config_gui_command(args):
  1291. """Launch the desktop settings window."""
  1292. from config_gui import launch
  1293. return launch()
  1294. def config_command(args):
  1295. """Dispatch bare `config`: GUI with --gui, otherwise the listing."""
  1296. if getattr(args, "gui", False):
  1297. return config_gui_command(args)
  1298. return config_list_command(args)
  1299. def _own_version(this_file: str) -> str:
  1300. """The version of the package copy this file belongs to, loaded from the
  1301. _version.py beside it by path, so another installed copy never answers."""
  1302. import importlib.util
  1303. spec = importlib.util.spec_from_file_location(
  1304. "_patent_creator_version", Path(this_file).resolve().with_name("_version.py")
  1305. )
  1306. module = importlib.util.module_from_spec(spec)
  1307. spec.loader.exec_module(module)
  1308. return module.load_version(this_file)
  1309. def main():
  1310. """
  1311. Main CLI entry point
  1312. """
  1313. parser = argparse.ArgumentParser(
  1314. description="Claude Patent Creator - Examiner-level patent creation",
  1315. formatter_class=argparse.RawDescriptionHelpFormatter,
  1316. epilog=_render("""
  1317. Examples:
  1318. patent-creator setup # Setup MPEP/USC/CFR sources
  1319. patent-creator status # Show MPEP installation status
  1320. patent-creator health # System health check
  1321. patent-creator verify-config # Verify Claude Code configuration
  1322. patent-creator serve # Run the MCP server
  1323. patent-creator rebuild-index # Rebuild MPEP index
  1324. patent-creator download-mpep # Download MPEP PDFs only
  1325. patent-creator download-all # Download all sources (MPEP + 35 USC + 37 CFR)
  1326. patent-creator check-bigquery # Check BigQuery connection
  1327. For more information: https://github.com/RobThePCGuy/Claude-Patent-Creator
  1328. """),
  1329. )
  1330. parser.add_argument("--version", action="version", version=f"patent-creator {_own_version(__file__)}")
  1331. subparsers = parser.add_subparsers(dest="command", help="Command to run")
  1332. # Check BigQuery command
  1333. check_bigquery_parser = subparsers.add_parser("check-bigquery", help="Check BigQuery authentication and availability")
  1334. check_bigquery_parser.set_defaults(func=check_bigquery_command)
  1335. # Setup command
  1336. setup_parser = subparsers.add_parser("setup", help="Download sources and build index")
  1337. setup_parser.add_argument("--rebuild", action="store_true", help="Force rebuild of index")
  1338. setup_parser.add_argument(
  1339. "--no-hyde",
  1340. action="store_true",
  1341. help="Disable HyDE query expansion (already off unless PATENT_MPEP_USE_HYDE=true)",
  1342. )
  1343. setup_parser.add_argument(
  1344. "--non-interactive",
  1345. action="store_true",
  1346. help="Skip interactive prompts (for CI/plugin use)",
  1347. )
  1348. setup_parser.set_defaults(func=setup_command)
  1349. # Serve command
  1350. serve_parser = subparsers.add_parser("serve", help="Run the MCP server")
  1351. serve_parser.add_argument(
  1352. "--no-hyde",
  1353. action="store_true",
  1354. help="Disable HyDE query expansion (already off unless PATENT_MPEP_USE_HYDE=true)",
  1355. )
  1356. serve_parser.set_defaults(func=run_server)
  1357. # Status command
  1358. status_parser = subparsers.add_parser("status", help="Show installation status")
  1359. status_parser.set_defaults(func=status_command)
  1360. # Health command (alias for status)
  1361. health_parser = subparsers.add_parser("health", help="System health check (alias for status)")
  1362. health_parser.set_defaults(func=health_command)
  1363. # Rebuild index command
  1364. rebuild_parser = subparsers.add_parser("rebuild-index", help="Rebuild MPEP index")
  1365. rebuild_parser.add_argument(
  1366. "--no-hyde",
  1367. action="store_true",
  1368. help="Disable HyDE query expansion (already off unless PATENT_MPEP_USE_HYDE=true)",
  1369. )
  1370. rebuild_parser.set_defaults(func=rebuild_index_command)
  1371. # Download MPEP command
  1372. download_mpep_parser = subparsers.add_parser("download-mpep", help="Download MPEP PDFs only")
  1373. download_mpep_parser.set_defaults(func=download_mpep_command)
  1374. # Download all command
  1375. download_all_parser = subparsers.add_parser("download-all", help="Download all sources (MPEP + 35 USC + 37 CFR)")
  1376. download_all_parser.set_defaults(func=download_all_command)
  1377. # Verify config command
  1378. verify_parser = subparsers.add_parser(
  1379. "verify-config", help="Verify Claude Code MCP configuration"
  1380. )
  1381. verify_parser.set_defaults(func=verify_config_command)
  1382. # Config command (view/edit settings)
  1383. config_parser = subparsers.add_parser(
  1384. "config", help="View or change settings (API keys, BigQuery cap, device, ...)"
  1385. )
  1386. config_parser.add_argument(
  1387. "--gui", action="store_true", help="Open the desktop settings window"
  1388. )
  1389. config_parser.set_defaults(func=config_command)
  1390. config_sub = config_parser.add_subparsers(dest="config_action")
  1391. config_sub.add_parser("list", help="List all settings and their values").set_defaults(
  1392. func=config_list_command
  1393. )
  1394. cfg_get = config_sub.add_parser("get", help="Print one setting's value")
  1395. cfg_get.add_argument("key")
  1396. cfg_get.set_defaults(func=config_get_command)
  1397. cfg_set = config_sub.add_parser("set", help="Set a setting in the config file")
  1398. cfg_set.add_argument("key")
  1399. cfg_set.add_argument("value")
  1400. cfg_set.set_defaults(func=config_set_command)
  1401. cfg_unset = config_sub.add_parser("unset", help="Remove a setting from the config file")
  1402. cfg_unset.add_argument("key")
  1403. cfg_unset.set_defaults(func=config_unset_command)
  1404. config_sub.add_parser("path", help="Print the config file path").set_defaults(
  1405. func=config_path_command
  1406. )
  1407. # Download patents command
  1408. args = parser.parse_args()
  1409. if not args.command:
  1410. parser.print_help()
  1411. return 0
  1412. # `config` is intentionally usable without the heavy server stack, so users
  1413. # can set credentials/options before everything else is installed.
  1414. if args.command != "config" and _SERVER_IMPORT_ERROR is not None:
  1415. print("[X] Could not load required dependencies.", file=sys.stderr)
  1416. detail = _SERVER_IMPORT_STDERR.strip() or str(_SERVER_IMPORT_ERROR)
  1417. if detail:
  1418. print(" " + detail.replace("\n", "\n "), file=sys.stderr)
  1419. print(
  1420. _render(
  1421. " Reinstall them with: pip install --upgrade "
  1422. "git+https://github.com/RobThePCGuy/Claude-Patent-Creator.git\n"
  1423. " (from a source checkout: pip install -e .), then retry.\n"
  1424. " ('patent-creator config' works without them.)"
  1425. ),
  1426. file=sys.stderr,
  1427. )
  1428. return 1
  1429. # Run the selected command
  1430. return args.func(args)
  1431. if __name__ == "__main__":
  1432. sys.exit(main())

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.