Skip to main content
Glama
john-walkoe

USPTO Patent File Wrapper MCP Server

by john-walkoe
README.md
# USPTO Patent File Wrapper MCP Server

A high-performance Model Context Protocol (MCP) server for the USPTO Patent File Wrapper API with token saving **context reduction** capabilities, smart field mapping, and **secure browser-accessible downloads**.

[![Platform Support](https://img.shields.io/badge/platform-Linux%20%7C%20Windows-blue.svg)]()
[![Python](https://img.shields.io/badge/python-3.10%2B-blue.svg)]()
[![API](https://img.shields.io/badge/API-USPTO%20Patent%20File%20Wrapper-green.svg)]()
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)

## πŸ“š Documentation

| Document | Description |
|----------|-------------|
| **[πŸ“₯ Installation Guide](INSTALL.md)** | Complete cross-platform setup with automated scripts |
| **[πŸ”‘ API Key Guide](API_KEY_GUIDE.md)** | Step-by-step instructions for obtaining USPTO and Mistral API keys with screenshots |
| **[πŸ“– Usage Examples](USAGE_EXAMPLES.md)** | Function examples, workflows, and integration patterns |
| **[🎯 Prompt Templates](PROMPTS.md)** | Detailed guide to sophisticated prompt templates for legal & research workflows |
| **[βš™οΈ Field Customization](CUSTOMIZATION.md)** | Comprehensive guidance on customizing field sets for the minimal and balanced tools |
| **[πŸ”’ Security Guidelines](SECURITY_GUIDELINES.md)** | Comprehensive security best practices |
| **[πŸ›‘οΈ Security Scanning](SECURITY_SCANNING.md)** | Automated secret detection and prompt injection protection guide |
| **[Content Provenance](docs/CONTENT_PROVENANCE.md)** | How retrieved document text is labeled and annotated (data-not-instructions posture) |
| **[πŸ§ͺ Testing Guide](tests/README.md)** | Test suite documentation and API key setup |
| **[βš–οΈ License](LICENSE)** | MIT License terms and conditions |

##  ⚑Quick Start

### Windows Install

**Run PowerShell as Administrator**, then:

```powershell
# Navigate to your user profile
cd $env:USERPROFILE

# If git is installed:
git clone https://github.com/john-walkoe/uspto_pfw_mcp.git
cd uspto_pfw_mcp

# If git is NOT installed:
# Download and extract the repository to C:\Users\YOUR_USERNAME\uspto_pfw_mcp
# Then navigate to the folder:
# cd C:\Users\YOUR_USERNAME\uspto_pfw_mcp

# The script detects if uv is installed and if it is not it will install uv - https://docs.astral.sh/uv

# Run setup script (sets execution policy for this session only):
Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope Process
.\deploy\windows_setup.ps1

# View INSTALL.md for sample script output.
# Close Powershell Window.
# If choose option to "configure Claude Desktop integration" during the script then restart Claude Desktop
```

The PowerShell script will:

- βœ… Check for and auto-install uv (via winget or PowerShell script)
- βœ… Install dependencies and create executable
- βœ… Prompt for USPTO API key (required) and Mistral API key (optional) or Detect if you had installed the developer's other USPTO MCPs and ask if want to use existing keys from those installation.
- πŸ”’ **If entering in API keys, the script will automatically store API keys securely using Windows DPAPI encryption**
- βœ… Ask if you want Claude Desktop integration configured
- πŸ”’ **Offer secure configuration method (recommended) or traditional method (API keys in plain text in the MCP JSON file)**
- βœ… Backups and then automatically merge with existing Claude Desktop config (preserves other MCP servers)
- βœ… Provide installation summary and next steps

### Claude Desktop Configuration - Manual installs

```json
{
  "mcpServers": {
    "uspto_pfw": {
      "command": "uv",
      "args": [
        "--directory",
        "C:/Users/YOUR_USERNAME/uspto_pfw_mcp",
        "run",
        "patent-filewrapper-mcp"
      ],
      "env": {
        "USPTO_API_KEY": "your_actual_USPTO_api_key_here",
        "MISTRAL_API_KEY": "your_mistral_api_key_here_OPTIONAL",
        "MISTRAL_OCR_MODEL": "mistral-ocr-latest_OPTIONAL_pin_a_dated_slug",
        "DOCLING_SERVE_URL": "http://localhost:5001",
        "PROXY_PORT": "8080"
      }
    }
  }
}
```

**For detailed installation, manual setup, and troubleshooting**, see **[INSTALL.md](./INSTALL.md)**

##  🎯Key Benefits

- **πŸ”’ Secure API Key Storage** - Windows DPAPI encryption for API keys (secure storage option during setup)
- **πŸ—ΊοΈ Smart Field Mapping** - Use simple names like `"inventionTitle"` instead of `"applicationMetaData.inventionTitle"`
- **βš™οΈ User-Customizable Fields** - Configure field sets through YAML without code changes
- **🎯 Context Reduction** - Get focused responses instead of massive API dumps
- **πŸ” Multi-Strategy Search** - Comprehensive, fuzzy, and exact inventor searches
- **⚑ Convenience Parameters** - Attorney-friendly search parameters (art_unit, examiner_name, applicant_name, etc.) eliminate need for complex query syntax
- **πŸ›οΈ Professional-Grade Fields** - additional fields for patent prosecution, international work, and analytics

- **πŸ”„ Circuit Breaker Resilience** - Automatic retry logic with exponential backoff prevents API failures
- **πŸ“Š Progressive Disclosure** - context reduction through optimized minimal β†’ balanced β†’ detailed workflows
- **πŸ”— Cross-MCP Integration** - Purpose-built for multi-database patent research with Developer's other PTAB, FPD, Citations, and Pinecone (Assistant or RAG) MCPs
  - **πŸ†• Centralized Document Hub** - PFW proxy now serves as unified download infrastructure for all USPTO MCPs (accepts FPD document registrations)
- **πŸ“ Attorney-Focused Prompt Templates** - 10+ sophisticated workflow templates for legal research, litigation, and due diligence (opt-in server-side: set `PFW_ENABLE_PROMPTS=true` to register them; off by default)

- **✨ Intelligent Document Extraction** - 4-tier hybrid extraction: USPTO free-text variants β†’ pypdf native text layer β†’ Mistral OCR β†’ Docling OCR (self-hosted, set `DOCLING_SERVE_URL`). Both OCR backends are optional
- **🌐 Secure Browser Downloads** - Click proxy URLs to download PDFs directly while keeping API keys secure
- **πŸ‘οΈ Advanced OCR Capabilities** - Extract text for LLM use from scanned PDFs, formulas, diagrams, and complex layouts via Mistral OCR or Docling (EasyOCR engine)
- **πŸ“ Document Bag Integration** - Full prosecution document access (Abstract, Claims, NOA, etc.) alongside XML content analysis of patents/applications
- **πŸš€ High Performance** - Optimized for AI workflows with targeted field selection + retry logic with exponential backoff
- **πŸ›‘οΈ Production Ready** - Enhanced error handling, structured logging with request IDs, and comprehensive security guidelines
- **πŸ’» Cross-Platform** - Works seamlessly on Linux and Windows
- **πŸ“‹ Complete API Coverage** - All USPTO Patent File Wrapper endpoints supported

## πŸ” Tool Search Optimization (Claude Code v2.1.7+)

**NEW**: PFW MCP now supports Claude Code's built-in tool search optimization, reducing context window usage by **65-75%** through dynamic tool discovery.

### How It Works

- **Automatic Activation**: When MCP tools exceed 10% of context, tool search activates automatically
- **Smart Discovery**: Claude loads only essential tools upfront, discovering others on-demand via MCPSearch
- **Token Savings**: ~8-12K tokens β†’ ~2-3K tokens (saves 5-10K tokens for actual work)
- **Zero Configuration**: Works out of the box with Claude Code v2.1.7+

### Entry Point Tools (Always Available)

These 3 tools are loaded immediately for fast access:

1. **`PFW_search_applications_minimal`** - Primary discovery for patent applications
2. **`PFW_get_guidance`** - Workflow guidance and documentation
3. **`PFW_get_application_documents`** - Document lists for patent applications

### Progressive Tool Discovery

Claude discovers additional tools as needed:

- **Tier 1 (Minimal)**: Fast, essential fields only (~10 fields)
- **Tier 2 (Balanced)**: Common use cases (~25 fields)
- **Tier 3 (Complete)**: All available data (~50+ fields)

### Enable Tool Search

If tool search isn't activating automatically:

**Windows**:
```powershell
$env:ENABLE_TOOL_SEARCH = "true"
claude
```

**Linux/Mac**:
```bash
export ENABLE_TOOL_SEARCH=true
claude
```

### Verify It's Working

Run `/context` in Claude Code:

```
MCP tools: loaded on-demand (N servers)  ← Tool search IS working
```

---

### Workflow Design - All preformed by the LLM with Minimal User Guidance

**User Requests the following:**

- *"Look for patents about LCD TV technology related to QLED"*
- *"Show me Apple's patent applications filed in 2024"*
- *"Get me PDFs download links for the patent "Integrated delivery and protection device for digital objects"*
- *"I need you to look at the patent details of 7971071 and summarize it for me"*
- *"Research this IPR case IPR2025-00562 and compare it to the original prosecution"* -* Requires that the USPTO Patent Trial and Appeal Board (PTAB) be installed - [uspto_ptab_mcp](https://github.com/john-walkoe/uspto_ptab_mcp.git) and also recommended to ask LLM to perform a PFW_get_guidance tool call prior to this or any cross MCP prompt (see quick reference chart for section selection, additional details in [Usage Examples](USAGE_EXAMPLES.md))

**LLM Performs these steps:**

**Step 1: Discovery minimal** β†’ **Step 2: Selection (and searches balanced - Optional)** β†’ **Step 3: Content Analysis** β†’ **Step 4 (Optional): Select additional prosecution documents for examination** β†’ **Step 5 (Optional): Retrieve doc_id(s) of the selected from documentBag** β†’ **Step 6 (Optional): Document Extraction for LLM use and/or Download Links of PDFs for user's use**

The field configuration supports an optimized research progression:

1. **Discovery searches minimal** return 20-50 applications efficiently without prosecution document bloat
2. **Selection (and searches balanced - Optional)** from the retrieved select likely application(s)/patent(s).  Optional balanced search(es) performed if needed in advanced workflows and/or USPTO PTAB (Patent Trial and Appeal Board) MCP cross workflows
3. **Content analysis** via XML retrieval for selected patents with structured data for LLM's use in analysis
4. **Select additional prosecution documents for examination** (Optional) e.g. Notice of Allowance, Applicant Citations (disclosed prior art), Examiner's Office Action Rejections, etc.
5. **Retrieve doc_id(s) of the selected from documentBag** (Optional) use get application documents tool to get the doc_id(s)
6. **Document Extraction for LLM use and/or Download Links of PDFs for user's use** (Optional) Document extraction via intelligent hybrid tool that auto-optimizes for speed and quality and Downloads of the documents as PDFs uses URLs from a HTTP proxy that obscures the USPTO's API key from chat history

##  🎯 Prompt Templates

This MCP server includes sophisticated AI-optimized prompt templates for complex patent workflows. For detailed documentation on all templates, features, and usage examples, see **[PROMPTS.md](PROMPTS.md)**.

### Quick Template Overview

| Category | Templates | Purpose |
|----------|-----------|---------|
| **Legal Analysis** | `/patent_search`, `/patent_explanation_for_attorneys`, `/patent_invalidity_analysis_defense_pinecone_PTAB` | Patent discovery, technical translation, defensive litigation |
| **Research & Prosecution** | `/art_unit_quality_assessment_FPD`, `/litigation_research_setup_PTAB_FPD`, `/technology_landscape_mapping_PTAB` | Examiner analysis, litigation prep, competitive intelligence |
| **Document Management** | `/complete_patent_package`, `/document_filtering_assistant`, `/inventor_portfolio_analysis` | Organized retrieval, smart filtering, portfolio mapping |

**Key Features Across All Templates:**
- **Enhanced Input Processing** - Flexible identifier support (patent numbers, application numbers, title keywords)
- **Smart Validation** - Automatic format detection and guidance
- **Cross-MCP Integration** - Seamless workflows with PTAB, FPD, Citations, and Pinecone MCPs
- **Context Optimization** - token reduction through progressive disclosure

## πŸ–ΌοΈ MCP Apps (Visual UI in Claude)

PFW MCP includes four built-in visual views rendered as iframes inside Claude Desktop (a fifth, the user-management panel, appears only on OAuth deployments with `PFW_ENABLE_USER_MANAGEMENT=true`):

| Trigger | View | What it shows |
|---------|------|---------------|
| Any `PFW_search_*` tool | Search Results | Results table with status/art unit filter pills, Patent Center links |
| `PFW_get_patent_or_application_xml` | Claims & Abstract Reader | Tabbed Claims / Abstract viewer with IND/DEP claim detection |
| `PFW_get_document_download` / `PFW_get_granted_patent_documents_download` | Recent Downloads | Last 10 downloaded documents with clickable PDF links |
| `PFW_get_family` | Patent Family | Generation-by-generation family tree with CON/CIP/DIV relation labels, Patent Center and Google Patents links |

MCP Apps require `FASTMCP_TRANSPORT=http` mode. Claude Desktop picks up the `ui://pfw/` resources automatically via the FastMCP 4 Apps extension (imported from `fastmcp.apps`).

##  πŸ“ŠAvailable Functions

> **Registered MCP tool names**: the tables below use the tools' display-style
> names. In `tools/list` the server registers 17 tools under these exact names:
> `PFW_search_applications`, `PFW_search_inventor`, `PFW_search_applications_minimal`,
> `PFW_search_applications_balanced`, `PFW_search_inventor_minimal`,
> `PFW_search_inventor_balanced`, `PFW_get_application_documents`,
> `PFW_get_patent_or_application_xml`, `PFW_get_granted_patent_documents_download`,
> `PFW_get_oa_rejections`, `PFW_get_oa_text`, `PFW_get_document_content_with_ocr`,
> `PFW_get_document_download`, `PFW_get_family`, `PFW_get_term_adjustment`,
> `PFW_get_guidance`, and (OAuth deployments with
> `PFW_ENABLE_USER_MANAGEMENT=true` only) `pfw_manage_users`.

### Identifier formats

A bare 8-digit number is simultaneously a valid US patent number and a valid
application serial (patent numbers passed 12,000,000 in 2024), so the tools
that take an identifier cannot tell them apart on their own. Resolution queries
the patent-number lane first and the application-serial lane second, and every
affected response reports `identifier_resolved_as`, `identifier_lanes_tried`
and, when the input was ambiguous, `identifier_ambiguous` plus an
`identifier_note`.

Write the identifier in a form that removes the ambiguity:

| You mean | Write it as | Why |
|----------|-------------|-----|
| Application serial 11/752,072 | `11/752,072` | A slash marks a serial unambiguously; resolution short-circuits to the application lane |
| Application serial, no slash available | `11752072` plus `content_type='application'` | Forces the application lane |
| Granted patent 7,971,071 | `7971071` or `7,971,071` | Seven digits or fewer is a patent number, unambiguous |
| Granted patent 11,752,072 | `11752072` or `11,752,072` | A comma-only number stays on the patent-first lane, which is what granted patents want |

`11752072` typed bare is therefore patent **11,752,072** (application
16816197, "QUICK SET CEMENTS FOR DENTAL PULP CAPPING AND RELATED METHODS OF
USE"), not application 11/752,072. Passing an unrecognized `content_type`
value is a 400, not a silent fall back to `auto`.

### Response markers (how a bounded or paged response says so)

An oversized tool result is replaced by a client-side truncation error the
server never sees, so responses are bounded server-side and every bound is
announced. Budgets are CHARACTER budgets (`len(json.dumps(...))`), never token
estimates. All four markers are **absent on a no-op** - an unbounded response
comes back byte-identical.

| Marker | Appears on | Carries |
|--------|-----------|---------|
| `_bounds` | any response slimmed or truncated to fit | `applied`, `reason` (`"size"` or `"window"`), `size_chars`, `size_limit`, `stages`, `slimmed_fields`, `items_returned`, `items_total`, `note` |
| `_window` | paged text (`PFW_get_document_content_with_ocr`, `PFW_get_oa_text`) | `unit` (`"char"` or `"page"`), `offset`, `returned`, `total`, `has_more`, `next_offset`, `note`. Feed `next_offset` back as `char_offset` to continue |
| `paging` | every search | `limit_requested`, `limit_applied`, `offset`, `returned`, `total`, `has_more`, `next_offset` |
| `limit_clamped` | a search asking for more than `MAX_SEARCH_LIMIT` (100) | `requested`, `applied`, `note`. The call CLAMPS and runs; it does not 400. `limit < 1` is still a 400 |

`PFW_get_guidance("limits")` prints the live budgets and the same contract.
Environment variables: `USPTO_MAX_RESPONSE_CHARS`, `USPTO_MAX_CONTENT_CHARS`,
`USPTO_RESPONSE_BOUNDS_ENABLED` (see [INSTALL.md](INSTALL.md#environment-variables)).

### Search Functions (6 Focused Tools)
| Function (Display Name) | Context Reduction | Use Case |
|----------|------------------|----------|
| `PFW_search_applications` (Search applications custom) | Variable | Custom patent search with user-defined fields |
| `PFW_search_inventor` (Search inventor custom) | Variable | Smart inventor search with multiple strategies |
| `PFW_search_applications_minimal` (Search applications minimal) | typical 95-99% | Ultra-fast search (user-customizable minimal fields) |
| `PFW_search_applications_balanced` (Search applications balanced) | typical 85-95% | Key fields for discovery (no documentBag) |
| `PFW_search_inventor_minimal` (Search inventor minimal) | typical 95-99% | Ultra-fast inventor search (user-customizable) |
| `PFW_search_inventor_balanced` (Search inventor balanced) | typical 85-95% | Balanced inventor search (no documentBag) |

##  Search Strategies

### Inventor Search Strategies

- **`exact`** - Exact name matching only
- **`fuzzy`** - Multiple name format variations
- **`comprehensive`** - All strategies + partial matching

### Query Examples

```python
# Exact strategy
"applicationMetaData.inventorBag.inventorNameText:\"John Smith\""

# Comprehensive strategy
[
  "applicationMetaData.inventorBag.inventorNameText:\"John Smith\"",
  "applicationMetaData.inventorBag.inventorNameText:\"Smith, John\"",
  "applicationMetaData.inventorBag.inventorNameText:Smith*",
  "applicationMetaData.inventorBag.inventorNameText:*Smith*"
]
```

### Document Processing Functions

| Function (Display Name)                                      | Purpose                                                      | Requirements                                       |
| ------------------------------------------------------------ | ------------------------------------------------------------ | -------------------------------------------------- |
| `PFW_get_patent_or_application_xml` (Get patent or application xml) | Get structured XML content for patents/applications for LLM use with **91-99% token reduction** via `include_raw_xml=False` (recommended) and optional `include_fields` for selective extraction | USPTO_API_KEY                                      |
| `PFW_get_granted_patent_documents_download` (Get granted patent documents download) | Get complete granted patent package (Abstract, Drawings, Specification, Claims) in one call as secure browser-accessible download URLs | USPTO_API_KEY                                      |
| `PFW_get_application_documents` (Get application documents)  | Get prosecution documents' doc_id from documentBag with advanced filtering (document_code, direction_category) | USPTO_API_KEY                                      |
| `PFW_get_document_content_with_ocr` (PFW get document content with ocr) | 4-tier hybrid text extraction: USPTO free-text variants β†’ pypdf native text layer β†’ Mistral OCR β†’ Docling OCR | USPTO_API_KEY (+ MISTRAL_API_KEY or DOCLING_SERVE_URL for scanned docs) |
| `PFW_get_document_download` (PFW get document download)      | Secure browser-accessible download URLs                      | USPTO_API_KEY                                      |
| `PFW_get_oa_rejections` (PFW get OA rejections)              | Search USPTO OA Rejections API v2 β€” rejection type indicators (Β§101/Β§102/Β§103/Β§112) by application/examiner/art unit | USPTO_API_KEY                                      |
| `PFW_get_oa_text` (PFW get OA text)                          | Search USPTO OA Actions API v1 β€” full office action body text and section-specific excerpts | USPTO_API_KEY                                      |
| `PFW_get_family` (PFW get family)                            | Normalized continuity family graph (nodes + edges with CON/CIP/DIV relation types, earliest ancestors) plus foreign priority claims. Optional depth-2 walk. | USPTO_API_KEY                                      |
| `PFW_get_term_adjustment` (PFW get term adjustment)          | Patent Term Adjustment from the ODP /adjustment endpoint: total days, A/B/C and applicant delay, capped event history. No expiration date is computed. | USPTO_API_KEY                                      |
| `PFW_get_guidance` (PFW get guidance)                        | **RECOMMENDED**: Context-efficient selective guidance sections (95-99% token reduction) | None                                               |

### Document Processing Capabilities

- **XML Content Tier (`PFW_get_patent_or_application_xml`)**: Structured patent/application content with **extreme context optimization**
  - **🎯 RECOMMENDED: `include_raw_xml=False`** - Removes ~50K token raw XML overhead (91% token reduction!)
  - **Selective field extraction (`include_fields`)** - Request only needed fields for 95-99% token reduction
  - **Default optimized response** - Returns abstract, claims, description (~5K tokens with `include_raw_xml=False`)
  - **Ultra-efficient modes** - Claims only (~1.5K tokens), Citations only (569 tokens), Inventors only (428 tokens)
  - **Intelligent patent-to-application mapping** - Automatically finds applications for granted patents
  - **Auto-detection** - Automatically determines patent vs application from identifier
  - **LLM-optimized parsing** - Extracts abstract, claims, inventors, classifications, citations on demand
  - **Dual XML support** - Handles both PTGRXML (granted patents) and APPXML (applications)
  - **Data limitation** - Only available for patents/applications filed after January 1, 2001
- **Complete Patent Package Tier (`PFW_get_granted_patent_documents_download`)**: Single-call granted patent retrieval
  - **All-in-one convenience** - Retrieves Abstract, Drawings, Specification, Claims in one call (replaces 4 separate calls)
  - **Intelligent component selection** - Auto-selects original vs. granted claims, optional drawings
  - **Organized download links** - Returns structured metadata with proxy download URLs for all components
  - **Perfect for attorneys** - Ideal for due diligence, litigation prep, portfolio review, hard copy generation
  - **Efficient workflow** - Use for 'give me the patent' requests instead of manual document hunting
  - **Graceful degradation** - Succeeds if 3+ of 4 components available, clearly indicates missing items
  - **LLM-optimized guidance** - Built-in formatting instructions for clickable markdown links
  - **Total page count** - Shows overall document size upfront for planning (typically 40-80 pages)
- **Prosecution Documents Tier (`PFW_get_application_documents`)**: - Targeted document access from documentBag
  - **Token-efficient design** - Get prosecution documents only when needed (no search bloat)
  - **Advanced filtering** - Filter by `document_code` (NOA, CTFR, 892, etc.) and `direction_category` (INCOMING/OUTGOING/INTERNAL)
  - **Context reduction** - Achieve 98.6% reduction for heavily-litigated applications (200+ docs β†’ 1-2 docs)
  - **Smart document filtering** - Focus on key documents (ABST, CLM, SPEC, NOA, etc.)
  - **Workflow optimization** - Use after discovery search for specific applications
  - **Document guidance** - Intelligent summary and download recommendations
  - **Replaces documentBag in search** - Prevents 100x token explosion in discovery workflows
- **✨ Intelligent Extraction Tier (`PFW_get_document_content_with_ocr`)**: - auto-optimized extraction
  - **Tier 0 β€” Free text variants** (instant, no OCR): the `.docx`, `xmlarchive`, or as-uploaded PDF the USPTO API serves alongside the PDF render (USPTO-authored papers and e-filed claims/remarks/IDS); each variant is checked against the requested application number
  - **Tier 1 β€” pypdf** (instant): Works on text-based PDFs; an all-empty text layer is reported as a failure, not a success
  - **Tier 2 - Mistral OCR**: Handles scanned USPTO documents; requires `MISTRAL_API_KEY` (optional)
  - **Tier 3 - Docling OCR**: Self-hosted EasyOCR via `DOCLING_SERVE_URL`; handles the same scanned documents as Mistral, and can be configured instead of Mistral rather than only after it
  - **Tier escalation** - An OCR tier runs only when the native text layer is missing or unusable; a tier with no credential or endpoint configured is skipped
  - **Transparent reporting** - Returns `extraction_method` in every response
  - **Unified interface** - Single tool handles all document types (eliminates tool confusion)
- **Browser Download Tier (`PFW_get_document_download`)**: Secure proxy downloads
  - **Click-to-download** URLs that work directly in any browser
  - **API key security** - USPTO API credentials never exposed in chat history or browser
  - **Rate limiting compliance** - Automatic enforcement of USPTO's 5 downloads per 10 seconds
  - **Enhanced filenames** - Professional, human-readable filenames for both PFW and FPD documents:
    - PFW: `APP-{app_number}_PAT-{patent_number}_{invention_title}_{type}.pdf`
    - FPD: `PET-{date}_APP-{app}_PAT-{patent}_{description}.pdf`
  - **Hybrid server architecture** - HTTP proxy runs alongside MCP server
  - **Adjustable TCP port** - HTTP proxy's TCP port can be adjusted by an environment variable
  - **πŸ†• Centralized proxy hub** - PFW proxy (port 8080) now accepts document registrations from FPD MCP for unified download experience across USPTO MCPs.  (Planned future PTAB centralized proxy hub)
  - **CORS locked to localhost by default** - Proxy and MCP App only accept requests from `localhost`; configurable for reverse proxy or MCP gateway deployments via `CORS_EXTRA_ORIGIN` and `MCP_APP_EXTRA_DOMAINS` env vars β€” see [INSTALL.md](INSTALL.md#environment-variables)

#### Enhanced Filename Format used in `PFW_get_document_download` and `PFW_get_granted_patent_documents_download`

The system automatically generates descriptive filenames using application metadata:

**For PFW Documents - Granted Patents:**
```
APP-11752072_PAT-7971071_INTEGRATED_DELIVERY_AND_PROTECTION_ABST.pdf
APP-14171705_PAT-9049188_HYBRID_DEVICE_HAVING_A_PERSONAL_DIGITAL_CLM.pdf
```

**For PFW Documents - Pending Applications:**
```
APP-18462633_SURFACE_DENSITY_DEVICE_CALIBRATION_APPARATU_SPEC.pdf
APP-18823722_BACK_CONTACT_SOLAR_CELL_AND_METHOD_FOR_PREP_DRW.pdf
```

**For FPD Documents - Petition Decisions:**

```
PET-2025-09-03_APP-13632078_PAT-8803593_PATENT_PROSECUTION_HIGHWAY_DECISION.pdf
PET-2024-05-15_APP-17414168_PAT-12252554_REVIVAL_PETITION_DECISION.pdf
```

> The application numbers inside a generated filename are the bare digits the
> USPTO API returns (`applicationNumberText`). When you TYPE an application
> serial into a tool, use the slash-comma form (`11/752,072`) instead: see
> [Identifier formats](#identifier-formats) above.

**Features:**
- **APP-** prefix for clear application number identification
- **PAT-** prefix shows the granted patent number (when available)
- **PET-** prefix for FPD petition documents with decision date
- **40-character titles** for better readability (PFW) or **40-character descriptions** (FPD)
- **Document type codes** (PFW: ABST, CLM, SPEC, DRW; FPD: DECISION, etc.)
- **Chronological sorting** - FPD filenames start with dates for easy timeline navigation
- **Cross-platform safe** characters and length limits
- **Portfolio-friendly** organization for patent attorneys

### LLM Guidance Functions

| Function (Display Name)               | Purpose                              | Requirements |
| ------------------------------------- | ------------------------------------ | ------------ |
| `PFW_get_guidance` (PFW get guidance) | Context-efficient selective guidance | None         |

#### Context-Efficient Guidance System

**NEW: `PFW_get_guidance` Tool** - Solves MCP Resources visibility problem with selective guidance sections:

🎯 **Quick Reference Chart** - Know exactly which section to call:
- πŸ” "Find patents by inventor/company/art unit" β†’ `PFW_get_guidance("fields")`
- πŸ“„ "Get complete patent package/documents" β†’ `PFW_get_guidance("documents")`
- πŸ”– "Decode document codes (NOA, CTFR, 892, etc.)" β†’ `PFW_get_guidance("document_codes")`
- 🀝 "Research IPR vs prosecution patterns" β†’ `PFW_get_guidance("workflows_ptab")`
- 🚩 "Analyze petition red flags + prosecution" β†’ `PFW_get_guidance("workflows_fpd")`
- πŸ“Š "Citation analysis for examiner behavior" β†’ `PFW_get_guidance("workflows_citations")`
- 🧠 "Domain-based RAG for legal framework (Β§101, Β§103, Β§112)" β†’ `PFW_get_guidance("workflows_pinecone")`
- 🏒 "Complete company due diligence" β†’ `PFW_get_guidance("workflows_complete")`
- βš™οΈ "Convenience parameter searches" β†’ `PFW_get_guidance("tools")`
- ❌ "Search errors or download issues" β†’ `PFW_get_guidance("errors")`
- ⚑ "Optimize extraction and context usage" β†’ `PFW_get_guidance("cost")`



##  Smart Field Mapping

Transform complex API field names into user-friendly alternatives:

```python
#  User-friendly (automatically mapped)
fields = [
    "applicationNumberText",    # Direct passthrough
    "inventionTitle",           # applicationMetaData.inventionTitle
    "patentNumber",             # applicationMetaData.patentNumber
    "filingDate",               # applicationMetaData.filingDate
    "parentPatentNumber"        # parentContinuityBag.parentPatentNumber
]

#  Advanced API paths (still supported)
fields = [
    "applicationMetaData.inventionTitle",
    "applicationMetaData.examinerNameText",
    "parentContinuityBag.parentApplicationNumberText"
]
```

### Supported Field Mappings
| User-Friendly | Maps To API Field |
|---------------|------------------|
| `inventionTitle` | `applicationMetaData.inventionTitle` |
| `patentNumber` | `applicationMetaData.patentNumber` |
| `filingDate` | `applicationMetaData.filingDate` |
| `applicationStatusDescriptionText` | `applicationMetaData.applicationStatusDescriptionText` |
| `firstInventorName` | `applicationMetaData.firstInventorName` |
| `parentPatentNumber` | `parentContinuityBag.parentPatentNumber` |
| `docketNumber` | `applicationMetaData.docketNumber` |

*Full mapping with 30+ fields available in `src/patent_filewrapper_mcp/api/helpers.py`*

## πŸ’» Usage Examples & Integration Workflows

For comprehensive usage examples, including:
- **Convenience parameter searches** (art unit, examiner, applicant, dates)
- **Advanced document filtering** (document codes, direction categories, context reduction)
- **Cross-MCP integration workflows** (PFW + PTAB + FPD + Pinecone)
- **Complete lifecycle due diligence** examples
- **Litigation research patterns**
- **Art unit quality assessment**
- **Extraction and context efficiency strategies**

See the detailed **[USAGE_EXAMPLES.md](USAGE_EXAMPLES.md)** documentation.

## πŸ”§ Field Customization

The MCP server supports user-customizable field sets through YAML configuration for optimal context reduction. You can modify field sets without changing any code!

**Configuration file:** `field_configs.yaml` (in project root)

For complete customization guidance, including progressive workflow strategies, token optimization, and advanced field selection patterns, see **[CUSTOMIZATION.md](CUSTOMIZATION.md)**.

## πŸ”— Cross-MCP Integration

This MCP is designed to work seamlessly with three other USPTO MCPs for comprehensive patent lifecycle analysis:

### Related USPTO MCP Servers

| MCP Server                                     | Purpose                                                      | GitHub Repository                                            |
| ---------------------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| **USPTO Patent File Wrapper (PFW)**            | Prosecution history & documents                              | [uspto_pfw_mcp](https://github.com/john-walkoe/uspto_pfw_mcp.git) |
| **USPTO Patent Trial and Appeal Board (PTAB)** | Patent Trial and Appeal Board proceedings                    | [uspto_ptab_mcp](https://github.com/john-walkoe/uspto_ptab_mcp.git) |
| **USPTO Enriched Citation**                    | Information about which references, or prior art, were cited in specific patent application office actions.  Uses [USPTO Enriched Citation API v3](https://developer.uspto.gov/api-catalog/uspto-enriched-citation-api-v3) | [uspto_enriched_citation_mcp](https://github.com/john-walkoe/uspto_enriched_citation_mcp.git) |
| **USPTO Final Petition Decisions (FPD)**       | Final Petition Decisions                                     | [uspto_fpd_mcp](https://github.com/john-walkoe/uspto_fpd_mcp.git) |
| **Pinecone Assistant MCP**                     | Patent law knowledge base with AI-powered chat and citations (MPEP, examination guidance) - 1 API key, limited free tier | [pinecone_assistant_mcp](https://github.com/john-walkoe/pinecone_assistant_mcp.git) |
| **Pinecone RAG MCP**                           | Patent law knowledge base with custom embeddings (MPEP, examination guidance) - Requires Pinecone + embedding model, monthly resetting free tier | [pinecone_rag_mcp](https://github.com/john-walkoe/pinecone_rag_mcp.git) |

### Integration Overview

The **Patent File Wrapper (PFW) MCP** serves as the foundation for patent research, providing prosecution history and document access. When combined with the other MCPs, it enables:

- **PFW + PTAB**: Cross-reference PTAB proceedings with prosecution history for litigation research
- **PFW + Enriched Citations**: AI-powered examiner citation analysis and prior art research patterns
- **PFW + FPD**: Understand petition history and procedural issues during prosecution
- **PFW + FPD + PTAB**: Complete patent lifecycle tracking from filing through post-grant challenges
- **PFW + Pinecone (Assistant or RAG)**: Research MPEP guidance before pulling full prosecution documents into context

### Key Integration Patterns

**Cross-Referencing Fields:**
- `applicationNumberText` - Primary key linking PTAB proceedings to PFW prosecution
- `groupArtUnitNumber` - Art unit analysis across all MCPs
- `examinerNameText` - Examiner behavior patterns and quality assessment
- `firstApplicantName` / `inventorBag` - Party matching across MCPs

**Progressive Workflow:**
1. **Discovery** (PFW): Find applications/patents using minimal search with convenience parameters
2. **Citation Analysis** (Enriched Citations): Analyze examiner citation patterns and prior art references
3. **Petition Check** (FPD): Review prosecution procedural history
4. **Challenge Assessment** (PTAB): Check for post-grant challenges
5. **Knowledge Research** (Pinecone): Research MPEP guidance if available (Assistant MCP: `assistant_context` / RAG MCP: `semantic_search`)
6. **Document Analysis** (PFW): Extract targeted prosecution documents

For detailed integration workflows, cross-referencing examples, and complete use cases, see [USAGE_EXAMPLES.md](USAGE_EXAMPLES.md#cross-mcp-integration-workflows).

##  πŸ“ˆPerformance Comparison

| Method | Response Size | Context Usage | Features |
|--------|---------------|---------------|----------|
| **Direct curl** | ~100KB+ | High | Raw API access |
| **MCP Balanced** | ~5KB | Medium | Key fields + mapping |
| **MCP Minimal** | ~1KB | Very Low | Essential data only |

##  πŸ§ͺTesting

### Step 1: Manual End-to-End Tests (Start Here)

Open Claude Desktop with this MCP server connected and paste the prompt from **[tests/TEST_SUITE.md](tests/TEST_SUITE.md)**. This runs 21 tests (Test 0 through Test 20) across the 12 tools it covers against the live USPTO API with known expected outputs - no code required. It does not exercise `PFW_get_family`, `PFW_get_term_adjustment`, `PFW_search_inventor` or `PFW_search_inventor_balanced`.

Run after initial setup, after upgrades, or after modifying tool logic.

### Step 2: Developer Tests

```bash
# Full test suite (pytest, asyncio_mode=auto)
# test_unified_key_management.py is excluded because it overwrites the real
# secure-storage keys mid-test β€” only run it deliberately.
uv run pytest --ignore=tests/test_unified_key_management.py

# If no download proxy is running on port 8080, skip the proxy integration test:
SKIP_PROXY_TESTS=1 uv run pytest --ignore=tests/test_unified_key_management.py

# Single-file smoke test
uv run python tests/test_fields_fix.py
```

For the full developer test suite including proxy server, OCR extraction, and API key setup, see the **[Testing Guide](tests/README.md)**.

##  πŸ“Project Structure

```
uspto_pfw_mcp/
β”œβ”€β”€ field_configs.yaml             # Root-level field customization
β”œβ”€β”€ launcher.py                     # Entry point launcher
β”œβ”€β”€ .security/                      # Security scanning components
β”‚   β”œβ”€β”€ patent_prompt_injection_detector.py # Enhanced prompt injection detection
β”‚   β”œβ”€β”€ check_prompt_injections.py # Standalone scanning script with baseline support
β”‚   └── .prompt_injections.baseline # Baseline tracking for prompt injection findings
β”œβ”€β”€ src/
β”‚   └── patent_filewrapper_mcp/
β”‚       β”œβ”€β”€ main.py                 # FastMCP server assembly (instructions, resources, tool registration)
β”‚       β”œβ”€β”€ server_bootstrap.py     # Entry point, transport selection, proxy lifecycle
β”‚       β”œβ”€β”€ fastmcp_compat.py       # FastMCP 4 / MCP SDK 2.x shims (defer_loading, tool titles)
β”‚       β”œβ”€β”€ middleware.py           # Streamable-HTTP probe shim and x-api-key gate
β”‚       β”œβ”€β”€ guidance.py             # PFW_get_guidance section bodies
β”‚       β”œβ”€β”€ app_uris.py             # ui://pfw/ MCP App resource URIs
β”‚       β”œβ”€β”€ client_registry.py      # Shared USPTO API client (lazy init)
β”‚       β”œβ”€β”€ __init__.py
β”‚       β”œβ”€β”€ __main__.py
β”‚       β”œβ”€β”€ exceptions.py
β”‚       β”œβ”€β”€ shared_secure_storage.py # Cross-platform secure API key storage (DPAPI / Fernet)
β”‚       β”œβ”€β”€ config/
β”‚       β”‚   β”œβ”€β”€ field_manager.py   # Configuration management
β”‚       β”‚   β”œβ”€β”€ tool_reflections.py # Migration notices (guidance moved to PFW_get_guidance)
β”‚       β”‚   └── log_config.py      # πŸ†• Logging configuration with file-based rotation
β”‚       β”œβ”€β”€ api/
β”‚       β”‚   β”œβ”€β”€ enhanced_client.py  # 4-tier extraction (free-text variants β†’ pypdf β†’ Mistral β†’ Docling)
β”‚       β”‚   β”œβ”€β”€ docling_client.py   # docling-serve REST client (self-hosted OCR via DOCLING_SERVE_URL)
β”‚       β”‚   β”œβ”€β”€ oa_rejections_client.py  # USPTO OA Rejections API v2
β”‚       β”‚   β”œβ”€β”€ oa_text_client.py   # USPTO OA Actions API v1
β”‚       β”‚   β”œβ”€β”€ field_constants.py # Field constant definitions
β”‚       β”‚   β”œβ”€β”€ helpers.py         # Field mapping & utilities
β”‚       β”‚   └── ppubs/             # Patent publication client
β”‚       β”œβ”€β”€ models/
β”‚       β”‚   β”œβ”€β”€ constants.py       # System constants
β”‚       β”‚   └── search_params.py   # Search parameter models
β”‚       β”œβ”€β”€ prompts/               # AI prompt templates
β”‚       β”‚   β”œβ”€β”€ patent_search.py
β”‚       β”‚   β”œβ”€β”€ patent_explanation_for_attorneys.py
β”‚       β”‚   β”œβ”€β”€ patent_invalidity_analysis_defense_Pinecone_PTAB_FPD_Citations.py
β”‚       β”‚   β”œβ”€β”€ litigation_research_setup_PTAB_FPD.py
β”‚       β”‚   β”œβ”€β”€ technology_landscape_mapping_PTAB.py
β”‚       β”‚   β”œβ”€β”€ art_unit_quality_assessment_FPD.py
β”‚       β”‚   β”œβ”€β”€ complete_patent_package_retrieval_PTAB_FPD.py
β”‚       β”‚   β”œβ”€β”€ document_filtering_assistant.py
β”‚       β”‚   β”œβ”€β”€ inventor_portfolio_analysis.py
β”‚       β”‚   β”œβ”€β”€ examiner_behavior_intelligence_CITATION.py
β”‚       β”‚   └── prior_art_analysis_CITATION.py
β”‚       β”œβ”€β”€ proxy/
β”‚       β”‚   β”œβ”€β”€ server.py          # HTTP proxy for secure downloads
β”‚       β”‚   β”œβ”€β”€ rate_limiter.py    # USPTO rate limiting compliance
β”‚       β”‚   β”œβ”€β”€ secure_link_cache.py
β”‚       β”‚   β”œβ”€β”€ models.py
β”‚       β”‚   β”œβ”€β”€ fpd_document_store.py
β”‚       β”‚   └── ptab_document_store.py
β”‚       β”œβ”€β”€ reflections/           # Reflection system (legacy)
β”‚       β”‚   β”œβ”€β”€ base_reflection.py
β”‚       β”‚   β”œβ”€β”€ pfw_reflections.py
β”‚       β”‚   └── reflection_manager.py
β”‚       β”œβ”€β”€ services/
β”‚       β”‚   └── ocr_service.py     # OCR quality detection and processing
β”‚       β”œβ”€β”€ tools/                 # MCP tool registration (search, documents, OA, guidance, admin)
β”‚       β”œβ”€β”€ auth/                  # Optional OAuth 2.1 sign-in (PFW_AUTH_MODE=oauth)
β”‚       β”œβ”€β”€ ui/                    # MCP App HTML views (ui://pfw/ resources)
β”‚       β”œβ”€β”€ shared/
β”‚       β”‚   β”œβ”€β”€ injection_scan.py  # Runtime detection-only injection scanner + provenance note
β”‚       β”‚   β”œβ”€β”€ internal_auth.py   # Shared authentication
β”‚       β”‚   β”œβ”€β”€ log_sanitizer.py   # Automatic sensitive data sanitization
β”‚       β”‚   β”œβ”€β”€ safe_logger.py     # Safe logger with auto-sanitization
β”‚       β”‚   β”œβ”€β”€ response_bounds.py # Shared response-size guard (_bounds / _window)
β”‚       β”‚   β”œβ”€β”€ fernet_key_store.py
β”‚       β”‚   └── uspto_shared_rate_limiter.py # Cross-process shared USPTO rate limiter
β”‚       β”œβ”€β”€ util/
β”‚       β”‚   β”œβ”€β”€ database.py
β”‚       β”‚   β”œβ”€β”€ dpapi_utils.py
β”‚       β”‚   β”œβ”€β”€ error_handlers.py
β”‚       β”‚   β”œβ”€β”€ identifier_normalization.py
β”‚       β”‚   β”œβ”€β”€ identifier_resolution.py # Patent-vs-application lane resolution
β”‚       β”‚   β”œβ”€β”€ linux_secret_store.py
β”‚       β”‚   β”œβ”€β”€ input_processing.py
β”‚       β”‚   β”œβ”€β”€ logging.py         # Enhanced logging utilities
β”‚       β”‚   β”œβ”€β”€ package_manager.py
β”‚       β”‚   └── security_logger.py
β”‚       └── json/
β”‚           └── search_query.json  # Sample JSON structures
β”œβ”€β”€ deploy/
β”‚   β”œβ”€β”€ linux_setup.sh            # Linux deployment script
β”‚   β”œβ”€β”€ windows_setup.ps1         # PowerShell deployment script
β”‚   β”œβ”€β”€ manage_api_keys.ps1       # API key management utilities
β”‚   β”œβ”€β”€ Validation-Helpers.psm1   # PowerShell validation module
β”‚   └── validation_helpers.sh     # Bash validation helpers
β”œβ”€β”€ tests/                         # Current test files (see tests/README.md for the full list)
β”‚   β”œβ”€β”€ README.md                  # Testing documentation
β”‚   β”œβ”€β”€ TEST_SUITE.md              # Manual end-to-end suite against the live USPTO API
β”‚   β”œβ”€β”€ conftest.py
β”‚   β”œβ”€β”€ test_fields_fix.py        # Core functionality test
β”‚   β”œβ”€β”€ test_proxy_simple.py      # Proxy server test
β”‚   β”œβ”€β”€ test_quality_detection.py # Extraction quality detection test
β”‚   β”œβ”€β”€ test_unified_key_management.py # Secure key storage test (excluded by default)
β”‚   β”œβ”€β”€ test_identifier_resolution_order.py # Resolve-then-validate order guard
β”‚   β”œβ”€β”€ test_response_bounds.py   # Shared response-size guard
β”‚   β”œβ”€β”€ test_download.py
β”‚   β”œβ”€β”€ test_enhanced_filename.py
β”‚   β”œβ”€β”€ test_fpd_integration.py
β”‚   β”œβ”€β”€ test_granted_patent_documents_download.py
β”‚   β”œβ”€β”€ test_injection_scan.py    # Runtime injection scanner + tool wiring tests
β”‚   β”œβ”€β”€ test_mistral_key_logic.py
β”‚   β”œβ”€β”€ test_optional_mistral.py
β”‚   β”œβ”€β”€ test_placeholder_detection.py
β”‚   β”œβ”€β”€ test_ptab_integration.py
β”‚   β”œβ”€β”€ test_resilience_features.py
β”‚   β”œβ”€β”€ test_tool_reflections.py
β”‚   └── test_utils.py
β”œβ”€β”€ reference/
β”‚   β”œβ”€β”€ README.md
β”‚   β”œβ”€β”€ Document_Descriptions_List.csv
β”‚   └── PatentFileWrapper_swagger.yaml
β”œβ”€β”€ scripts/
β”‚   β”œβ”€β”€ manage_mcp_users.py       # Bootstrap and manage the OAuth mcp_users table
β”‚   └── rotate_internal_auth_secret.py # Rolling rotation for INTERNAL_AUTH_SECRET
β”œβ”€β”€ docs/
β”‚   └── CONTENT_PROVENANCE.md     # Retrieved-text provenance and injection-annotation posture
β”œβ”€β”€ pyproject.toml                 # Package configuration
β”œβ”€β”€ uv.lock                        # uv lockfile
β”œβ”€β”€ README.md                      # This file
β”œβ”€β”€ INSTALL.md                     # Comprehensive installation guide
β”œβ”€β”€ USAGE_EXAMPLES.md             # Function examples and workflows
β”œβ”€β”€ CUSTOMIZATION.md              # Field configuration and optimization guide
β”œβ”€β”€ PROMPTS.md                    # Prompt templates documentation
β”œβ”€β”€ API_KEY_GUIDE.md             # USPTO and optional Mistral key setup
β”œβ”€β”€ SSO_SETUP.md                 # OAuth 2.1 sign-in (Google / Entra ID)
β”œβ”€β”€ SECURITY_GUIDELINES.md       # Security best practices
β”œβ”€β”€ SECURITY_SCANNING.md         # Automated secret detection guide
└── .env.example                 # Every environment variable, commented
```

##  πŸ”Troubleshooting

### Common Issues

#### API Key Issues
- **For Claude Desktop:** API keys in config file are sufficient
- **For test scripts:** Environment variables must be set

**Setting USPTO API Key:**
- **Windows Command Prompt:** `set USPTO_API_KEY=your_key`
- **Windows PowerShell:** `$env:USPTO_API_KEY="your_key"`
- **Linux/macOS:** `export USPTO_API_KEY=your_key`

**Setting Mistral API Key (for OCR):**
- **Windows Command Prompt:** `set MISTRAL_API_KEY=your_key`
- **Windows PowerShell:** `$env:MISTRAL_API_KEY="your_key"`
- **Linux/macOS:** `export MISTRAL_API_KEY=your_key`

#### uv vs pip Issues
- **uv advantages:** Better dependency resolution, faster installs
- **Mixed installation:** Can use both `uv sync` and `pip install -e .`
- **Testing:** Use `uv run` prefix for uv-managed projects

#### Fields Not Returning Data
- **Cause:** Field name not in mapping
- **Solution:** Add to `field_mapping` in `helpers.py` or use full API field name

#### Authentication Errors
- **Cause:** Missing or invalid API key
- **Solution:** Verify `USPTO_API_KEY` environment variable or Claude Desktop config

#### MCP Server Won't Start
- **Cause:** Missing dependencies or incorrect paths
- **Solution:** Re-run setup script, restart all PowerShell windows, restart Claude Desktop (or other MCP Client) and verify configuration
- **If problems persist:** Reset the MCP installation (see "Resetting MCP Installation" below)

#### Virtual Environment Issues (Windows Setup)
- **Symptom:** "No pyvenv.cfg file" errors during `windows_setup.ps1`
- **Cause:** Claude Desktop locks `.venv` files when running, preventing proper virtual environment creation
- **Solution:**
  1. Close Claude Desktop completely before running setup script
  2. Remove `.venv` folder: `Remove-Item ./.venv -Force -Recurse -ErrorAction SilentlyContinue`
  3. Run `.\deploy\windows_setup.ps1` again

#### Resetting MCP Installation

**If you need to completely reset the MCP installation to run the Windows Quick installer again:**

```powershell
# Navigate to the project directory
cd C:\Users\YOUR_USERNAME\uspto_pfw_mcp

# Remove Python cache directories
Get-ChildItem -Path ./src -Directory -Recurse -Force | Where-Object { $_.Name -eq '__pycache__' } | Remove-Item -Recurse -Force

# Remove virtual environment
if (Test-Path ".venv") {
    Remove-Item ./.venv -Force -Recurse -ErrorAction SilentlyContinue
}

# Remove database files
Remove-Item ./proxy_link_cache.db -Force -ErrorAction SilentlyContinue
Remove-Item ./fpd_documents.db -Force -ErrorAction SilentlyContinue
Remove-Item ./ptab_documents.db -Force -ErrorAction SilentlyContinue

# Now you can run the setup script again
.\deploy\windows_setup.ps1
```

**Linux/macOS Reset:**
```bash
# Navigate to the project directory
cd ~/uspto_pfw_mcp

# Remove Python cache directories
find ./src -type d -name '__pycache__' -exec rm -rf {} + 2>/dev/null || true

# Remove virtual environment and database files
rm -rf .venv
rm -f proxy_link_cache.db fpd_documents.db ptab_documents.db

# Run setup script again
./deploy/linux_setup.sh
```

### Getting Help
1. Check the test scripts for working examples
2. Review the field mapping in `src/patent_filewrapper_mcp/api/helpers.py`
3. Verify your Claude Desktop configuration matches the provided templates in INSTALL.md

## πŸ›‘οΈ Security & Production Readiness

### Enhanced Error Handling
- **Retry logic with exponential backoff** - Automatic retries for transient failures (3 attempts with 1s, 2s, 4s delays)
- **Smart retry strategy** - Doesn't retry authentication errors or client errors (4xx)
- **Structured logging** - Request ID tracking for better debugging and monitoring
- **Production-grade resilience** - Handles timeouts, network issues, and API rate limits gracefully

### Security Features
- **Environment variable API keys** - No hardcoded credentials anywhere in codebase
- **Secure test patterns** - Test files use environment variables with fallbacks
- **Comprehensive .gitignore** - Prevents accidental credential commits
- **Security guidelines** - Complete documentation for secure development practices
- **CORS restricted to localhost** - Proxy and MCP App reject cross-origin requests by default; configurable for reverse proxy/gateway via `CORS_EXTRA_ORIGIN` / `MCP_APP_EXTRA_DOMAINS` (see [INSTALL.md](INSTALL.md#environment-variables))
- **Automated secret scanning** - CI/CD and pre-commit hooks prevent API key leaks (detect-secrets)
- **20+ secret types detected** - AWS keys, GitHub tokens, JWT, private keys, API keys, and more
- **Baseline management** - Tracks known placeholders while catching real secrets
- **πŸ†• SafeLogger with auto-sanitization** - Automatically masks API keys, JWTs, passwords, IPs, emails in all log messages (CWE-532)
- **πŸ†• File-based logging with rotation** - Persistent audit trail with 10MB rotation, 5/10 backups (CWE-778)
- **πŸ†• Prompt injection baseline system** - Tracks known findings, only flags NEW patterns with SHA256 fingerprinting
- **Prompt injection detection** - 70+ pattern detection system protects against AI-specific attacks
- **Patent-specific security** - Custom patterns detect USPTO API bypass and data extraction attempts
- **Enhanced filtering** - Minimizes false positives while maintaining comprehensive threat coverage

### Content Provenance & Injection Annotation

Retrieved prosecution text is served verbatim β€” nothing is stripped or
rewritten, because verbatim fidelity of legal text is the product. Instead,
the server labels and annotates:

- **`provenance_note`** β€” every text-returning tool
  (`PFW_get_document_content_with_ocr`, `PFW_get_oa_text`,
  `PFW_get_patent_or_application_xml`) attaches a machine-readable note stating
  that retrieved file-wrapper text is quoted data, not instructions, and that
  applicant- or examiner-drafted characterizations are attributed positions.
- **`injection_scan`** β€” a detection-only runtime scanner
  (`src/patent_filewrapper_mcp/shared/injection_scan.py`) checks returned OCR
  output, office-action text, and XML content for instruction-override,
  prompt-extraction, and encoding-evasion language and for suspicious
  densities of invisible Unicode. On a hit, the response gains an annotation
  naming the flagged document and the kinds of pattern found β€” never the
  matched text. The key is absent entirely when content is clean.
- **Server instructions** state the same posture so consuming models treat
  instruction-like language inside retrieved documents as quoted content to
  report, not directives to follow.

This runtime layer is complementary to the commit-time codebase scanner in
`.security/` (see [SECURITY_SCANNING.md](SECURITY_SCANNING.md)). Full write-up:
[docs/CONTENT_PROVENANCE.md](docs/CONTENT_PROVENANCE.md).

### Request Tracking & Debugging
All API requests include unique request IDs (8-char UUIDs) for correlation:
```
[a1b2c3d4] Starting GET request to applications/search
[a1b2c3d4] Request successful on attempt 1
```

### Documentation
- `SECURITY_GUIDELINES.md` - Comprehensive security best practices
- `SECURITY_SCANNING.md` - Automated secret detection and prevention guide
- `tests/README.md` - Complete testing guide with API key setup
- Enhanced error messages with request IDs for better support

##  πŸ“Contributing

1. Fork the repository
2. Create a feature branch
3. Add tests for new functionality
4. Ensure all tests pass
5. Submit a pull request

##  πŸ“„License

MIT License

## ⚠️ Disclaimer

**THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTY OF ANY KIND.**

**Independent Project Notice**: This is an independent personal project and is not affiliated with, endorsed by, or sponsored by the United States Patent and Trademark Office (USPTO).

The author makes no representations or warranties, express or implied, including but not limited to:

- **Accuracy & AI-Generated Content**: No guarantee of data accuracy, completeness, or fitness for any purpose. Users are specifically cautioned that outputs generated or assisted by Artificial Intelligence (AI) components, including but not limited to text, data, or analyses, may be inaccurate, incomplete, fictionalized, or represent "hallucinations" (confabulations) by the AI model.
- **Availability**: USPTO API and Mistral API dependencies may cause service interruptions.
- **Legal Compliance**: Users are solely responsible for ensuring their use of this software, and any submissions or actions taken based on its outputs, strictly comply with all applicable laws, regulations, and policies, including but not limited to:
  - The latest [Guidance on Use of Artificial Intelligence-Based Tools in Practice Before the United States Patent and Trademark Office](https://www.federalregister.gov/documents/2024/04/11/2024-07629/guidance-on-use-of-artificial-intelligence-based-tools-in-practice-before-the-united-states-patent) (USPTO Guidance).
  - The USPTO's Duty of Candor and Good Faith (e.g., 37 CFR 1.56, 11.303), which includes a duty to disclose material information and correct errors.
  - The USPTO's signature requirements (e.g., 37 CFR 1.4(d), 2.193(c), 11.18), certifying human review and reasonable inquiry.
  - All rules regarding inventorship (e.g., each claimed invention must have at least one human inventor).
- **Legal Advice**: This tool provides data access and processing only, not legal counsel. All results must be independently verified, critically analyzed, and professionally judged by qualified legal professionals.
- **Commercial Use**: Users must verify USPTO and Mistral terms for commercial applications.
- **Confidentiality & Data Security**: The author makes no representations regarding the confidentiality or security of any data, including client-sensitive or technical information, input by the user into the software's AI components or transmitted to third-party AI services (e.g., Mistral API). Users are responsible for understanding and accepting the privacy policies, data retention practices, and security measures of any integrated third-party AI services.
- **Foreign Filing Licenses & Export Controls**: Users are solely responsible for ensuring that the input or processing of any data, particularly technical information, through this software's AI components does not violate U.S. foreign filing license requirements (e.g., 35 U.S.C. 184, 37 CFR Part 5) or export control regulations (e.g., EAR, ITAR). This includes awareness of potential "deemed exports" if foreign persons access such data or if AI servers are located outside the United States.

**LIMITATION OF LIABILITY:** Under no circumstances shall the author be liable for any direct, indirect, incidental, special, or consequential damages arising from use of this software, even if advised of the possibility of such damages.

### USER RESPONSIBILITY: YOU ARE SOLELY RESPONSIBLE FOR THE INTEGRITY AND COMPLIANCE OF ALL FILINGS AND ACTIONS TAKEN BEFORE THE USPTO.

- **Independent Verification**: All outputs, analyses, and content generated or assisted by AI within this software MUST be thoroughly reviewed, independently verified, and corrected by a human prior to any reliance, action, or submission to the USPTO or any other entity. This includes factual assertions, legal contentions, citations, evidentiary support, and technical disclosures.
- **Duty of Candor & Good Faith**: You must adhere to your duty of candor and good faith with the USPTO, including the disclosure of any material information (e.g., regarding inventorship or errors) and promptly correcting any inaccuracies in the record.
- **Signature & Certification**: You must personally sign or insert your signature on any correspondence submitted to the USPTO, certifying your personal review and reasonable inquiry into its contents, as required by 37 CFR 11.18(b). AI tools cannot sign documents, nor can they perform the required human inquiry.
- **Confidential Information**: DO NOT input confidential, proprietary, or client-sensitive information into the AI components of this software without full client consent and a clear understanding of the data handling practices of the underlying AI providers. You are responsible for preventing inadvertent or unauthorized disclosure.
- **Export Controls**: Be aware of and comply with all foreign filing license and export control regulations when using this tool with sensitive technical data.
- **Service Compliance**: Ensure compliance with all USPTO (e.g., Terms of Use for USPTO websites, USPTO.gov account policies, restrictions on automated data mining) and Mistral terms of service. AI tools cannot obtain USPTO.gov accounts.
- **Security**: Maintain secure handling of API credentials and client information.
- **Testing**: Test thoroughly before production use.
- **Professional Judgment**: This tool is a supplement, not a substitute, for your own professional judgment and expertise.

**By using this software, you acknowledge that you have read this disclaimer and agree to use the software at your own risk, accepting full responsibility for all outcomes and compliance with relevant legal and ethical obligations.**

> **Note for Legal Professionals:** While this tool provides access to patent research tools commonly used in legal practice, it is a data retrieval and AI-assisted processing system only. All results require independent verification, critical professional analysis, and cannot substitute for qualified legal counsel or the exercise of your personal professional judgment and duties outlined in the USPTO Guidance on AI Use.

##  πŸ”—Related Links

- [USPTO Open Data Portal](https://data.uspto.gov/myodp)
- [USPTO Enriched Citation API v3](https://developer.uspto.gov/api-catalog/uspto-enriched-citation-api-v3)
- [USPTO Patent Trial and Appeal Board (PTAB) API v2](https://developer.uspto.gov/api-catalog/ptab-api-v2-migrating-odp-soon)
- [Model Context Protocol](https://modelcontextprotocol.io)
- [Claude](https://claude.ai)
- [uv Package Manager](https://github.com/astral-sh/uv)
- [Mistral OCR](https://mistral.ai/solutions/document-ai)

## πŸ’ Support This Project

If you find this USPTO Patent File Wrapper MCP Server useful, please consider supporting the development! This project was developed during my personal time over many hours to provide a comprehensive, production-ready tool for the patent community.

[![Donate with PayPal](https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif)](https://paypal.me/walkoe)

Your support helps maintain and improve this open-source tool for everyone in the patent community. Thank you!

##  Acknowledgments

- [USPTO](https://www.uspto.gov/) for providing the Patent File Wrapper API
- [Model Context Protocol](https://modelcontextprotocol.io/) for the MCP specification
- **[Claude Code](https://claude.ai/code)** for exceptional development assistance, architectural guidance, documentation creation, PowerShell automation, test organization, and comprehensive code development throughout this project
- **[Claude Desktop](https://claude.ai)** for additional development support and testing assistance

---

**Questions?** See [INSTALL.md](INSTALL.md) for complete cross-platform installation guide or review the test scripts for working examples.

## OAuth sign-in (optional)

Set `PFW_AUTH_MODE=oauth` to protect the HTTP endpoint with Google +
Microsoft sign-in (OAuth 2.1 with dynamic client registration β€” works as a
Claude.ai / Claude Desktop custom connector). Access is controlled by a local
SQLite user list; role `admin` unlocks the `pfw_manage_users` user-management
tool and its MCP App panel. The tool itself is registered only when
`PFW_ENABLE_USER_MANAGEMENT=true` (default off β€” in STDIO and non-OAuth HTTP
use `scripts/manage_mcp_users.py` instead). The default (`none`) and STDIO
are unchanged. Full walkthrough: [SSO_SETUP.md](SSO_SETUP.md).

## Shared USPTO rate limiting (multi-MCP deployments)

If you run all 4 USPTO MCPs (Citations, PFW, PTAB, FPD) as HTTP containers
on the **same box**, serving multiple users, under **one** USPTO API key,
each server's own in-process limiter can't see what the other 3 processes
are doing β€” and USPTO's documented limits are per-key (burst=1, 4-15
req/sec depending on call type, plus weekly quotas), not per-process. Point
all 4 containers at one bind-mounted directory and they share a single
cross-process token bucket + a bounded pool of in-flight-request slots,
arbitrated via POSIX file locks (crash-safe β€” a dead process's lock is
released by the kernel). Single-MCP or STDIO deployments need nothing; the
limiter is off unless the directory variable is set.

```yaml
# docker-compose.yml (excerpt, all 4 USPTO MCP services)
volumes:
  uspto-rate-limit: {}
services:
  pfw-mcp:
    volumes:
      - uspto-rate-limit:/var/run/uspto-shared-rate-limit
    environment:
      USPTO_SHARED_RATE_LIMIT_DIR: /var/run/uspto-shared-rate-limit
      USPTO_SHARED_RATE_LIMIT_RPS: "4"       # default; total across ALL 4 MCPs
      USPTO_SHARED_MAX_CONCURRENT: "2"       # default; shared in-flight slots
```

One token bucket and 2 concurrency slots are shared across every process
mounting the directory β€” a heavier MCP naturally draws more of the budget
under load, and a long PDF download occupies a slot for its full duration
(not just connection setup), per USPTO's burst=1 guidance.