feat: MCP server, API keys, OAuth, and KPI dashboard (#72)
* fix: prevent Chrome auto-translate from crashing React during onboarding
Chrome auto-translate modifies DOM text nodes when it detects a Swedish
page (lang="sv") in a browser set to English. React does not expect
external DOM mutations and throws, crashing the entire component tree
into global-error.tsx on every step transition.
Add translate="no" and <meta name="google" content="notranslate"> to
suppress browser translation. Also fix timezone-unsafe date parsing in
fiscal period validation (new Date("YYYY-MM-DD") + getDate() returns
local-timezone values, shifting dates by -1 day in Western timezones).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: add notranslate meta tag to global-error.tsx for consistency
Per review feedback — global-error.tsx renders its own <html> document,
so it needs the same <meta name="google" content="notranslate"> tag as
layout.tsx to fully suppress Chrome translation on error pages.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat: add MCP server extension with OAuth, API keys, and KPI dashboard
Let users do bookkeeping through Claude Desktop, Claude Code, or any
MCP-compatible client. "Show my uncategorized transactions." "Book that
as office supplies." "Invoice Acme for 15,000 kr."
MCP server (extension):
- 10 tools: transactions, categorization, customers, invoices,
trial balance, VAT report, KPI report, income statement
- JSON-RPC 2.0 protocol (no SDK dependency, works in serverless)
- Tool annotations, pagination, input validation per MCP best practices
- Same engine as web UI (VAT rules, exchange rates, event emission)
API key infrastructure (core):
- api_keys table with RLS, rate limiting (100 RPM), scopes column
- Atomic rate limit via DB RPC (validate_and_increment_api_key)
- Key management API routes + settings UI panel
OAuth 2.1 for Claude Desktop connectors:
- .well-known/oauth-protected-resource + oauth-authorization-server
- Authorization endpoint with consent page
- Token endpoint with PKCE verification
- Stateless encrypted auth codes (AES-256-GCM, no DB storage)
- Dynamic client registration
KPI dashboard:
- /nyckeltal page with hero cards, operational grid, trend chart
- GET /api/reports/kpi endpoint
- Gross margin, cash position, expense ratio, avg payment days,
VAT liability, revenue/expense trend
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: address OAuth security vulnerabilities from code review
Critical fixes:
- Auth code replay: Track used codes in oauth_used_codes table with
unique constraint. Codes are single-use per OAuth 2.1 §4.1.2.
- Open redirect: Validate redirect_uri against hardcoded allowlist
of known Claude callback URLs + localhost for dev.
P1 fixes:
- Move API key creation from /authorize to /token endpoint. Keys are
only created after PKCE verification, preventing orphaned keys on
abandoned OAuth flows.
- Add ensureInitialized() to MCP server so event handlers load and
transaction.categorized events reach extensions.
P2 fixes:
- Remove 'plain' from PKCE methods — only S256 is advertised and
accepted.
- Fix extension count in sectors test (10 → 11 for mcp-server).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: remove duplicate ensureInitialized() that caused circular import
The extension router (ext/[...path]/route.ts) already calls
ensureInitialized() before dispatching to handlers. The duplicate
call in server.ts created a circular import that Turbopack couldn't
resolve, breaking the Vercel build.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.6
parent
2b75ef6538
commit
5d66dd6bfc
@@ -0,0 +1,236 @@
|
||||
---
|
||||
name: mcp-builder
|
||||
description: Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when building MCP servers to integrate external APIs or services, whether in Python (FastMCP) or Node/TypeScript (MCP SDK).
|
||||
license: Complete terms in LICENSE.txt
|
||||
---
|
||||
|
||||
# MCP Server Development Guide
|
||||
|
||||
## Overview
|
||||
|
||||
Create MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. The quality of an MCP server is measured by how well it enables LLMs to accomplish real-world tasks.
|
||||
|
||||
---
|
||||
|
||||
# Process
|
||||
|
||||
## 🚀 High-Level Workflow
|
||||
|
||||
Creating a high-quality MCP server involves four main phases:
|
||||
|
||||
### Phase 1: Deep Research and Planning
|
||||
|
||||
#### 1.1 Understand Modern MCP Design
|
||||
|
||||
**API Coverage vs. Workflow Tools:**
|
||||
Balance comprehensive API endpoint coverage with specialized workflow tools. Workflow tools can be more convenient for specific tasks, while comprehensive coverage gives agents flexibility to compose operations. Performance varies by client—some clients benefit from code execution that combines basic tools, while others work better with higher-level workflows. When uncertain, prioritize comprehensive API coverage.
|
||||
|
||||
**Tool Naming and Discoverability:**
|
||||
Clear, descriptive tool names help agents find the right tools quickly. Use consistent prefixes (e.g., `github_create_issue`, `github_list_repos`) and action-oriented naming.
|
||||
|
||||
**Context Management:**
|
||||
Agents benefit from concise tool descriptions and the ability to filter/paginate results. Design tools that return focused, relevant data. Some clients support code execution which can help agents filter and process data efficiently.
|
||||
|
||||
**Actionable Error Messages:**
|
||||
Error messages should guide agents toward solutions with specific suggestions and next steps.
|
||||
|
||||
#### 1.2 Study MCP Protocol Documentation
|
||||
|
||||
**Navigate the MCP specification:**
|
||||
|
||||
Start with the sitemap to find relevant pages: `https://modelcontextprotocol.io/sitemap.xml`
|
||||
|
||||
Then fetch specific pages with `.md` suffix for markdown format (e.g., `https://modelcontextprotocol.io/specification/draft.md`).
|
||||
|
||||
Key pages to review:
|
||||
- Specification overview and architecture
|
||||
- Transport mechanisms (streamable HTTP, stdio)
|
||||
- Tool, resource, and prompt definitions
|
||||
|
||||
#### 1.3 Study Framework Documentation
|
||||
|
||||
**Recommended stack:**
|
||||
- **Language**: TypeScript (high-quality SDK support and good compatibility in many execution environments e.g. MCPB. Plus AI models are good at generating TypeScript code, benefiting from its broad usage, static typing and good linting tools)
|
||||
- **Transport**: Streamable HTTP for remote servers, using stateless JSON (simpler to scale and maintain, as opposed to stateful sessions and streaming responses). stdio for local servers.
|
||||
|
||||
**Load framework documentation:**
|
||||
|
||||
- **MCP Best Practices**: [📋 View Best Practices](./reference/mcp_best_practices.md) - Core guidelines
|
||||
|
||||
**For TypeScript (recommended):**
|
||||
- **TypeScript SDK**: Use WebFetch to load `https://raw.githubusercontent.com/modelcontextprotocol/typescript-sdk/main/README.md`
|
||||
- [⚡ TypeScript Guide](./reference/node_mcp_server.md) - TypeScript patterns and examples
|
||||
|
||||
**For Python:**
|
||||
- **Python SDK**: Use WebFetch to load `https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/main/README.md`
|
||||
- [🐍 Python Guide](./reference/python_mcp_server.md) - Python patterns and examples
|
||||
|
||||
#### 1.4 Plan Your Implementation
|
||||
|
||||
**Understand the API:**
|
||||
Review the service's API documentation to identify key endpoints, authentication requirements, and data models. Use web search and WebFetch as needed.
|
||||
|
||||
**Tool Selection:**
|
||||
Prioritize comprehensive API coverage. List endpoints to implement, starting with the most common operations.
|
||||
|
||||
---
|
||||
|
||||
### Phase 2: Implementation
|
||||
|
||||
#### 2.1 Set Up Project Structure
|
||||
|
||||
See language-specific guides for project setup:
|
||||
- [⚡ TypeScript Guide](./reference/node_mcp_server.md) - Project structure, package.json, tsconfig.json
|
||||
- [🐍 Python Guide](./reference/python_mcp_server.md) - Module organization, dependencies
|
||||
|
||||
#### 2.2 Implement Core Infrastructure
|
||||
|
||||
Create shared utilities:
|
||||
- API client with authentication
|
||||
- Error handling helpers
|
||||
- Response formatting (JSON/Markdown)
|
||||
- Pagination support
|
||||
|
||||
#### 2.3 Implement Tools
|
||||
|
||||
For each tool:
|
||||
|
||||
**Input Schema:**
|
||||
- Use Zod (TypeScript) or Pydantic (Python)
|
||||
- Include constraints and clear descriptions
|
||||
- Add examples in field descriptions
|
||||
|
||||
**Output Schema:**
|
||||
- Define `outputSchema` where possible for structured data
|
||||
- Use `structuredContent` in tool responses (TypeScript SDK feature)
|
||||
- Helps clients understand and process tool outputs
|
||||
|
||||
**Tool Description:**
|
||||
- Concise summary of functionality
|
||||
- Parameter descriptions
|
||||
- Return type schema
|
||||
|
||||
**Implementation:**
|
||||
- Async/await for I/O operations
|
||||
- Proper error handling with actionable messages
|
||||
- Support pagination where applicable
|
||||
- Return both text content and structured data when using modern SDKs
|
||||
|
||||
**Annotations:**
|
||||
- `readOnlyHint`: true/false
|
||||
- `destructiveHint`: true/false
|
||||
- `idempotentHint`: true/false
|
||||
- `openWorldHint`: true/false
|
||||
|
||||
---
|
||||
|
||||
### Phase 3: Review and Test
|
||||
|
||||
#### 3.1 Code Quality
|
||||
|
||||
Review for:
|
||||
- No duplicated code (DRY principle)
|
||||
- Consistent error handling
|
||||
- Full type coverage
|
||||
- Clear tool descriptions
|
||||
|
||||
#### 3.2 Build and Test
|
||||
|
||||
**TypeScript:**
|
||||
- Run `npm run build` to verify compilation
|
||||
- Test with MCP Inspector: `npx @modelcontextprotocol/inspector`
|
||||
|
||||
**Python:**
|
||||
- Verify syntax: `python -m py_compile your_server.py`
|
||||
- Test with MCP Inspector
|
||||
|
||||
See language-specific guides for detailed testing approaches and quality checklists.
|
||||
|
||||
---
|
||||
|
||||
### Phase 4: Create Evaluations
|
||||
|
||||
After implementing your MCP server, create comprehensive evaluations to test its effectiveness.
|
||||
|
||||
**Load [✅ Evaluation Guide](./reference/evaluation.md) for complete evaluation guidelines.**
|
||||
|
||||
#### 4.1 Understand Evaluation Purpose
|
||||
|
||||
Use evaluations to test whether LLMs can effectively use your MCP server to answer realistic, complex questions.
|
||||
|
||||
#### 4.2 Create 10 Evaluation Questions
|
||||
|
||||
To create effective evaluations, follow the process outlined in the evaluation guide:
|
||||
|
||||
1. **Tool Inspection**: List available tools and understand their capabilities
|
||||
2. **Content Exploration**: Use READ-ONLY operations to explore available data
|
||||
3. **Question Generation**: Create 10 complex, realistic questions
|
||||
4. **Answer Verification**: Solve each question yourself to verify answers
|
||||
|
||||
#### 4.3 Evaluation Requirements
|
||||
|
||||
Ensure each question is:
|
||||
- **Independent**: Not dependent on other questions
|
||||
- **Read-only**: Only non-destructive operations required
|
||||
- **Complex**: Requiring multiple tool calls and deep exploration
|
||||
- **Realistic**: Based on real use cases humans would care about
|
||||
- **Verifiable**: Single, clear answer that can be verified by string comparison
|
||||
- **Stable**: Answer won't change over time
|
||||
|
||||
#### 4.4 Output Format
|
||||
|
||||
Create an XML file with this structure:
|
||||
|
||||
```xml
|
||||
<evaluation>
|
||||
<qa_pair>
|
||||
<question>Find discussions about AI model launches with animal codenames. One model needed a specific safety designation that uses the format ASL-X. What number X was being determined for the model named after a spotted wild cat?</question>
|
||||
<answer>3</answer>
|
||||
</qa_pair>
|
||||
<!-- More qa_pairs... -->
|
||||
</evaluation>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
# Reference Files
|
||||
|
||||
## 📚 Documentation Library
|
||||
|
||||
Load these resources as needed during development:
|
||||
|
||||
### Core MCP Documentation (Load First)
|
||||
- **MCP Protocol**: Start with sitemap at `https://modelcontextprotocol.io/sitemap.xml`, then fetch specific pages with `.md` suffix
|
||||
- [📋 MCP Best Practices](./reference/mcp_best_practices.md) - Universal MCP guidelines including:
|
||||
- Server and tool naming conventions
|
||||
- Response format guidelines (JSON vs Markdown)
|
||||
- Pagination best practices
|
||||
- Transport selection (streamable HTTP vs stdio)
|
||||
- Security and error handling standards
|
||||
|
||||
### SDK Documentation (Load During Phase 1/2)
|
||||
- **Python SDK**: Fetch from `https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/main/README.md`
|
||||
- **TypeScript SDK**: Fetch from `https://raw.githubusercontent.com/modelcontextprotocol/typescript-sdk/main/README.md`
|
||||
|
||||
### Language-Specific Implementation Guides (Load During Phase 2)
|
||||
- [🐍 Python Implementation Guide](./reference/python_mcp_server.md) - Complete Python/FastMCP guide with:
|
||||
- Server initialization patterns
|
||||
- Pydantic model examples
|
||||
- Tool registration with `@mcp.tool`
|
||||
- Complete working examples
|
||||
- Quality checklist
|
||||
|
||||
- [⚡ TypeScript Implementation Guide](./reference/node_mcp_server.md) - Complete TypeScript guide with:
|
||||
- Project structure
|
||||
- Zod schema patterns
|
||||
- Tool registration with `server.registerTool`
|
||||
- Complete working examples
|
||||
- Quality checklist
|
||||
|
||||
### Evaluation Guide (Load During Phase 4)
|
||||
- [✅ Evaluation Guide](./reference/evaluation.md) - Complete evaluation creation guide with:
|
||||
- Question creation guidelines
|
||||
- Answer verification strategies
|
||||
- XML format specifications
|
||||
- Example questions and answers
|
||||
- Running an evaluation with the provided scripts
|
||||
@@ -0,0 +1,602 @@
|
||||
# MCP Server Evaluation Guide
|
||||
|
||||
## Overview
|
||||
|
||||
This document provides guidance on creating comprehensive evaluations for MCP servers. Evaluations test whether LLMs can effectively use your MCP server to answer realistic, complex questions using only the tools provided.
|
||||
|
||||
---
|
||||
|
||||
## Quick Reference
|
||||
|
||||
### Evaluation Requirements
|
||||
- Create 10 human-readable questions
|
||||
- Questions must be READ-ONLY, INDEPENDENT, NON-DESTRUCTIVE
|
||||
- Each question requires multiple tool calls (potentially dozens)
|
||||
- Answers must be single, verifiable values
|
||||
- Answers must be STABLE (won't change over time)
|
||||
|
||||
### Output Format
|
||||
```xml
|
||||
<evaluation>
|
||||
<qa_pair>
|
||||
<question>Your question here</question>
|
||||
<answer>Single verifiable answer</answer>
|
||||
</qa_pair>
|
||||
</evaluation>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Purpose of Evaluations
|
||||
|
||||
The measure of quality of an MCP server is NOT how well or comprehensively the server implements tools, but how well these implementations (input/output schemas, docstrings/descriptions, functionality) enable LLMs with no other context and access ONLY to the MCP servers to answer realistic and difficult questions.
|
||||
|
||||
## Evaluation Overview
|
||||
|
||||
Create 10 human-readable questions requiring ONLY READ-ONLY, INDEPENDENT, NON-DESTRUCTIVE, and IDEMPOTENT operations to answer. Each question should be:
|
||||
- Realistic
|
||||
- Clear and concise
|
||||
- Unambiguous
|
||||
- Complex, requiring potentially dozens of tool calls or steps
|
||||
- Answerable with a single, verifiable value that you identify in advance
|
||||
|
||||
## Question Guidelines
|
||||
|
||||
### Core Requirements
|
||||
|
||||
1. **Questions MUST be independent**
|
||||
- Each question should NOT depend on the answer to any other question
|
||||
- Should not assume prior write operations from processing another question
|
||||
|
||||
2. **Questions MUST require ONLY NON-DESTRUCTIVE AND IDEMPOTENT tool use**
|
||||
- Should not instruct or require modifying state to arrive at the correct answer
|
||||
|
||||
3. **Questions must be REALISTIC, CLEAR, CONCISE, and COMPLEX**
|
||||
- Must require another LLM to use multiple (potentially dozens of) tools or steps to answer
|
||||
|
||||
### Complexity and Depth
|
||||
|
||||
4. **Questions must require deep exploration**
|
||||
- Consider multi-hop questions requiring multiple sub-questions and sequential tool calls
|
||||
- Each step should benefit from information found in previous questions
|
||||
|
||||
5. **Questions may require extensive paging**
|
||||
- May need paging through multiple pages of results
|
||||
- May require querying old data (1-2 years out-of-date) to find niche information
|
||||
- The questions must be DIFFICULT
|
||||
|
||||
6. **Questions must require deep understanding**
|
||||
- Rather than surface-level knowledge
|
||||
- May pose complex ideas as True/False questions requiring evidence
|
||||
- May use multiple-choice format where LLM must search different hypotheses
|
||||
|
||||
7. **Questions must not be solvable with straightforward keyword search**
|
||||
- Do not include specific keywords from the target content
|
||||
- Use synonyms, related concepts, or paraphrases
|
||||
- Require multiple searches, analyzing multiple related items, extracting context, then deriving the answer
|
||||
|
||||
### Tool Testing
|
||||
|
||||
8. **Questions should stress-test tool return values**
|
||||
- May elicit tools returning large JSON objects or lists, overwhelming the LLM
|
||||
- Should require understanding multiple modalities of data:
|
||||
- IDs and names
|
||||
- Timestamps and datetimes (months, days, years, seconds)
|
||||
- File IDs, names, extensions, and mimetypes
|
||||
- URLs, GIDs, etc.
|
||||
- Should probe the tool's ability to return all useful forms of data
|
||||
|
||||
9. **Questions should MOSTLY reflect real human use cases**
|
||||
- The kinds of information retrieval tasks that HUMANS assisted by an LLM would care about
|
||||
|
||||
10. **Questions may require dozens of tool calls**
|
||||
- This challenges LLMs with limited context
|
||||
- Encourages MCP server tools to reduce information returned
|
||||
|
||||
11. **Include ambiguous questions**
|
||||
- May be ambiguous OR require difficult decisions on which tools to call
|
||||
- Force the LLM to potentially make mistakes or misinterpret
|
||||
- Ensure that despite AMBIGUITY, there is STILL A SINGLE VERIFIABLE ANSWER
|
||||
|
||||
### Stability
|
||||
|
||||
12. **Questions must be designed so the answer DOES NOT CHANGE**
|
||||
- Do not ask questions that rely on "current state" which is dynamic
|
||||
- For example, do not count:
|
||||
- Number of reactions to a post
|
||||
- Number of replies to a thread
|
||||
- Number of members in a channel
|
||||
|
||||
13. **DO NOT let the MCP server RESTRICT the kinds of questions you create**
|
||||
- Create challenging and complex questions
|
||||
- Some may not be solvable with the available MCP server tools
|
||||
- Questions may require specific output formats (datetime vs. epoch time, JSON vs. MARKDOWN)
|
||||
- Questions may require dozens of tool calls to complete
|
||||
|
||||
## Answer Guidelines
|
||||
|
||||
### Verification
|
||||
|
||||
1. **Answers must be VERIFIABLE via direct string comparison**
|
||||
- If the answer can be re-written in many formats, clearly specify the output format in the QUESTION
|
||||
- Examples: "Use YYYY/MM/DD.", "Respond True or False.", "Answer A, B, C, or D and nothing else."
|
||||
- Answer should be a single VERIFIABLE value such as:
|
||||
- User ID, user name, display name, first name, last name
|
||||
- Channel ID, channel name
|
||||
- Message ID, string
|
||||
- URL, title
|
||||
- Numerical quantity
|
||||
- Timestamp, datetime
|
||||
- Boolean (for True/False questions)
|
||||
- Email address, phone number
|
||||
- File ID, file name, file extension
|
||||
- Multiple choice answer
|
||||
- Answers must not require special formatting or complex, structured output
|
||||
- Answer will be verified using DIRECT STRING COMPARISON
|
||||
|
||||
### Readability
|
||||
|
||||
2. **Answers should generally prefer HUMAN-READABLE formats**
|
||||
- Examples: names, first name, last name, datetime, file name, message string, URL, yes/no, true/false, a/b/c/d
|
||||
- Rather than opaque IDs (though IDs are acceptable)
|
||||
- The VAST MAJORITY of answers should be human-readable
|
||||
|
||||
### Stability
|
||||
|
||||
3. **Answers must be STABLE/STATIONARY**
|
||||
- Look at old content (e.g., conversations that have ended, projects that have launched, questions answered)
|
||||
- Create QUESTIONS based on "closed" concepts that will always return the same answer
|
||||
- Questions may ask to consider a fixed time window to insulate from non-stationary answers
|
||||
- Rely on context UNLIKELY to change
|
||||
- Example: if finding a paper name, be SPECIFIC enough so answer is not confused with papers published later
|
||||
|
||||
4. **Answers must be CLEAR and UNAMBIGUOUS**
|
||||
- Questions must be designed so there is a single, clear answer
|
||||
- Answer can be derived from using the MCP server tools
|
||||
|
||||
### Diversity
|
||||
|
||||
5. **Answers must be DIVERSE**
|
||||
- Answer should be a single VERIFIABLE value in diverse modalities and formats
|
||||
- User concept: user ID, user name, display name, first name, last name, email address, phone number
|
||||
- Channel concept: channel ID, channel name, channel topic
|
||||
- Message concept: message ID, message string, timestamp, month, day, year
|
||||
|
||||
6. **Answers must NOT be complex structures**
|
||||
- Not a list of values
|
||||
- Not a complex object
|
||||
- Not a list of IDs or strings
|
||||
- Not natural language text
|
||||
- UNLESS the answer can be straightforwardly verified using DIRECT STRING COMPARISON
|
||||
- And can be realistically reproduced
|
||||
- It should be unlikely that an LLM would return the same list in any other order or format
|
||||
|
||||
## Evaluation Process
|
||||
|
||||
### Step 1: Documentation Inspection
|
||||
|
||||
Read the documentation of the target API to understand:
|
||||
- Available endpoints and functionality
|
||||
- If ambiguity exists, fetch additional information from the web
|
||||
- Parallelize this step AS MUCH AS POSSIBLE
|
||||
- Ensure each subagent is ONLY examining documentation from the file system or on the web
|
||||
|
||||
### Step 2: Tool Inspection
|
||||
|
||||
List the tools available in the MCP server:
|
||||
- Inspect the MCP server directly
|
||||
- Understand input/output schemas, docstrings, and descriptions
|
||||
- WITHOUT calling the tools themselves at this stage
|
||||
|
||||
### Step 3: Developing Understanding
|
||||
|
||||
Repeat steps 1 & 2 until you have a good understanding:
|
||||
- Iterate multiple times
|
||||
- Think about the kinds of tasks you want to create
|
||||
- Refine your understanding
|
||||
- At NO stage should you READ the code of the MCP server implementation itself
|
||||
- Use your intuition and understanding to create reasonable, realistic, but VERY challenging tasks
|
||||
|
||||
### Step 4: Read-Only Content Inspection
|
||||
|
||||
After understanding the API and tools, USE the MCP server tools:
|
||||
- Inspect content using READ-ONLY and NON-DESTRUCTIVE operations ONLY
|
||||
- Goal: identify specific content (e.g., users, channels, messages, projects, tasks) for creating realistic questions
|
||||
- Should NOT call any tools that modify state
|
||||
- Will NOT read the code of the MCP server implementation itself
|
||||
- Parallelize this step with individual sub-agents pursuing independent explorations
|
||||
- Ensure each subagent is only performing READ-ONLY, NON-DESTRUCTIVE, and IDEMPOTENT operations
|
||||
- BE CAREFUL: SOME TOOLS may return LOTS OF DATA which would cause you to run out of CONTEXT
|
||||
- Make INCREMENTAL, SMALL, AND TARGETED tool calls for exploration
|
||||
- In all tool call requests, use the `limit` parameter to limit results (<10)
|
||||
- Use pagination
|
||||
|
||||
### Step 5: Task Generation
|
||||
|
||||
After inspecting the content, create 10 human-readable questions:
|
||||
- An LLM should be able to answer these with the MCP server
|
||||
- Follow all question and answer guidelines above
|
||||
|
||||
## Output Format
|
||||
|
||||
Each QA pair consists of a question and an answer. The output should be an XML file with this structure:
|
||||
|
||||
```xml
|
||||
<evaluation>
|
||||
<qa_pair>
|
||||
<question>Find the project created in Q2 2024 with the highest number of completed tasks. What is the project name?</question>
|
||||
<answer>Website Redesign</answer>
|
||||
</qa_pair>
|
||||
<qa_pair>
|
||||
<question>Search for issues labeled as "bug" that were closed in March 2024. Which user closed the most issues? Provide their username.</question>
|
||||
<answer>sarah_dev</answer>
|
||||
</qa_pair>
|
||||
<qa_pair>
|
||||
<question>Look for pull requests that modified files in the /api directory and were merged between January 1 and January 31, 2024. How many different contributors worked on these PRs?</question>
|
||||
<answer>7</answer>
|
||||
</qa_pair>
|
||||
<qa_pair>
|
||||
<question>Find the repository with the most stars that was created before 2023. What is the repository name?</question>
|
||||
<answer>data-pipeline</answer>
|
||||
</qa_pair>
|
||||
</evaluation>
|
||||
```
|
||||
|
||||
## Evaluation Examples
|
||||
|
||||
### Good Questions
|
||||
|
||||
**Example 1: Multi-hop question requiring deep exploration (GitHub MCP)**
|
||||
```xml
|
||||
<qa_pair>
|
||||
<question>Find the repository that was archived in Q3 2023 and had previously been the most forked project in the organization. What was the primary programming language used in that repository?</question>
|
||||
<answer>Python</answer>
|
||||
</qa_pair>
|
||||
```
|
||||
|
||||
This question is good because:
|
||||
- Requires multiple searches to find archived repositories
|
||||
- Needs to identify which had the most forks before archival
|
||||
- Requires examining repository details for the language
|
||||
- Answer is a simple, verifiable value
|
||||
- Based on historical (closed) data that won't change
|
||||
|
||||
**Example 2: Requires understanding context without keyword matching (Project Management MCP)**
|
||||
```xml
|
||||
<qa_pair>
|
||||
<question>Locate the initiative focused on improving customer onboarding that was completed in late 2023. The project lead created a retrospective document after completion. What was the lead's role title at that time?</question>
|
||||
<answer>Product Manager</answer>
|
||||
</qa_pair>
|
||||
```
|
||||
|
||||
This question is good because:
|
||||
- Doesn't use specific project name ("initiative focused on improving customer onboarding")
|
||||
- Requires finding completed projects from specific timeframe
|
||||
- Needs to identify the project lead and their role
|
||||
- Requires understanding context from retrospective documents
|
||||
- Answer is human-readable and stable
|
||||
- Based on completed work (won't change)
|
||||
|
||||
**Example 3: Complex aggregation requiring multiple steps (Issue Tracker MCP)**
|
||||
```xml
|
||||
<qa_pair>
|
||||
<question>Among all bugs reported in January 2024 that were marked as critical priority, which assignee resolved the highest percentage of their assigned bugs within 48 hours? Provide the assignee's username.</question>
|
||||
<answer>alex_eng</answer>
|
||||
</qa_pair>
|
||||
```
|
||||
|
||||
This question is good because:
|
||||
- Requires filtering bugs by date, priority, and status
|
||||
- Needs to group by assignee and calculate resolution rates
|
||||
- Requires understanding timestamps to determine 48-hour windows
|
||||
- Tests pagination (potentially many bugs to process)
|
||||
- Answer is a single username
|
||||
- Based on historical data from specific time period
|
||||
|
||||
**Example 4: Requires synthesis across multiple data types (CRM MCP)**
|
||||
```xml
|
||||
<qa_pair>
|
||||
<question>Find the account that upgraded from the Starter to Enterprise plan in Q4 2023 and had the highest annual contract value. What industry does this account operate in?</question>
|
||||
<answer>Healthcare</answer>
|
||||
</qa_pair>
|
||||
```
|
||||
|
||||
This question is good because:
|
||||
- Requires understanding subscription tier changes
|
||||
- Needs to identify upgrade events in specific timeframe
|
||||
- Requires comparing contract values
|
||||
- Must access account industry information
|
||||
- Answer is simple and verifiable
|
||||
- Based on completed historical transactions
|
||||
|
||||
### Poor Questions
|
||||
|
||||
**Example 1: Answer changes over time**
|
||||
```xml
|
||||
<qa_pair>
|
||||
<question>How many open issues are currently assigned to the engineering team?</question>
|
||||
<answer>47</answer>
|
||||
</qa_pair>
|
||||
```
|
||||
|
||||
This question is poor because:
|
||||
- The answer will change as issues are created, closed, or reassigned
|
||||
- Not based on stable/stationary data
|
||||
- Relies on "current state" which is dynamic
|
||||
|
||||
**Example 2: Too easy with keyword search**
|
||||
```xml
|
||||
<qa_pair>
|
||||
<question>Find the pull request with title "Add authentication feature" and tell me who created it.</question>
|
||||
<answer>developer123</answer>
|
||||
</qa_pair>
|
||||
```
|
||||
|
||||
This question is poor because:
|
||||
- Can be solved with a straightforward keyword search for exact title
|
||||
- Doesn't require deep exploration or understanding
|
||||
- No synthesis or analysis needed
|
||||
|
||||
**Example 3: Ambiguous answer format**
|
||||
```xml
|
||||
<qa_pair>
|
||||
<question>List all the repositories that have Python as their primary language.</question>
|
||||
<answer>repo1, repo2, repo3, data-pipeline, ml-tools</answer>
|
||||
</qa_pair>
|
||||
```
|
||||
|
||||
This question is poor because:
|
||||
- Answer is a list that could be returned in any order
|
||||
- Difficult to verify with direct string comparison
|
||||
- LLM might format differently (JSON array, comma-separated, newline-separated)
|
||||
- Better to ask for a specific aggregate (count) or superlative (most stars)
|
||||
|
||||
## Verification Process
|
||||
|
||||
After creating evaluations:
|
||||
|
||||
1. **Examine the XML file** to understand the schema
|
||||
2. **Load each task instruction** and in parallel using the MCP server and tools, identify the correct answer by attempting to solve the task YOURSELF
|
||||
3. **Flag any operations** that require WRITE or DESTRUCTIVE operations
|
||||
4. **Accumulate all CORRECT answers** and replace any incorrect answers in the document
|
||||
5. **Remove any `<qa_pair>`** that require WRITE or DESTRUCTIVE operations
|
||||
|
||||
Remember to parallelize solving tasks to avoid running out of context, then accumulate all answers and make changes to the file at the end.
|
||||
|
||||
## Tips for Creating Quality Evaluations
|
||||
|
||||
1. **Think Hard and Plan Ahead** before generating tasks
|
||||
2. **Parallelize Where Opportunity Arises** to speed up the process and manage context
|
||||
3. **Focus on Realistic Use Cases** that humans would actually want to accomplish
|
||||
4. **Create Challenging Questions** that test the limits of the MCP server's capabilities
|
||||
5. **Ensure Stability** by using historical data and closed concepts
|
||||
6. **Verify Answers** by solving the questions yourself using the MCP server tools
|
||||
7. **Iterate and Refine** based on what you learn during the process
|
||||
|
||||
---
|
||||
|
||||
# Running Evaluations
|
||||
|
||||
After creating your evaluation file, you can use the provided evaluation harness to test your MCP server.
|
||||
|
||||
## Setup
|
||||
|
||||
1. **Install Dependencies**
|
||||
|
||||
```bash
|
||||
pip install -r scripts/requirements.txt
|
||||
```
|
||||
|
||||
Or install manually:
|
||||
```bash
|
||||
pip install anthropic mcp
|
||||
```
|
||||
|
||||
2. **Set API Key**
|
||||
|
||||
```bash
|
||||
export ANTHROPIC_API_KEY=your_api_key_here
|
||||
```
|
||||
|
||||
## Evaluation File Format
|
||||
|
||||
Evaluation files use XML format with `<qa_pair>` elements:
|
||||
|
||||
```xml
|
||||
<evaluation>
|
||||
<qa_pair>
|
||||
<question>Find the project created in Q2 2024 with the highest number of completed tasks. What is the project name?</question>
|
||||
<answer>Website Redesign</answer>
|
||||
</qa_pair>
|
||||
<qa_pair>
|
||||
<question>Search for issues labeled as "bug" that were closed in March 2024. Which user closed the most issues? Provide their username.</question>
|
||||
<answer>sarah_dev</answer>
|
||||
</qa_pair>
|
||||
</evaluation>
|
||||
```
|
||||
|
||||
## Running Evaluations
|
||||
|
||||
The evaluation script (`scripts/evaluation.py`) supports three transport types:
|
||||
|
||||
**Important:**
|
||||
- **stdio transport**: The evaluation script automatically launches and manages the MCP server process for you. Do not run the server manually.
|
||||
- **sse/http transports**: You must start the MCP server separately before running the evaluation. The script connects to the already-running server at the specified URL.
|
||||
|
||||
### 1. Local STDIO Server
|
||||
|
||||
For locally-run MCP servers (script launches the server automatically):
|
||||
|
||||
```bash
|
||||
python scripts/evaluation.py \
|
||||
-t stdio \
|
||||
-c python \
|
||||
-a my_mcp_server.py \
|
||||
evaluation.xml
|
||||
```
|
||||
|
||||
With environment variables:
|
||||
```bash
|
||||
python scripts/evaluation.py \
|
||||
-t stdio \
|
||||
-c python \
|
||||
-a my_mcp_server.py \
|
||||
-e API_KEY=abc123 \
|
||||
-e DEBUG=true \
|
||||
evaluation.xml
|
||||
```
|
||||
|
||||
### 2. Server-Sent Events (SSE)
|
||||
|
||||
For SSE-based MCP servers (you must start the server first):
|
||||
|
||||
```bash
|
||||
python scripts/evaluation.py \
|
||||
-t sse \
|
||||
-u https://example.com/mcp \
|
||||
-H "Authorization: Bearer token123" \
|
||||
-H "X-Custom-Header: value" \
|
||||
evaluation.xml
|
||||
```
|
||||
|
||||
### 3. HTTP (Streamable HTTP)
|
||||
|
||||
For HTTP-based MCP servers (you must start the server first):
|
||||
|
||||
```bash
|
||||
python scripts/evaluation.py \
|
||||
-t http \
|
||||
-u https://example.com/mcp \
|
||||
-H "Authorization: Bearer token123" \
|
||||
evaluation.xml
|
||||
```
|
||||
|
||||
## Command-Line Options
|
||||
|
||||
```
|
||||
usage: evaluation.py [-h] [-t {stdio,sse,http}] [-m MODEL] [-c COMMAND]
|
||||
[-a ARGS [ARGS ...]] [-e ENV [ENV ...]] [-u URL]
|
||||
[-H HEADERS [HEADERS ...]] [-o OUTPUT]
|
||||
eval_file
|
||||
|
||||
positional arguments:
|
||||
eval_file Path to evaluation XML file
|
||||
|
||||
optional arguments:
|
||||
-h, --help Show help message
|
||||
-t, --transport Transport type: stdio, sse, or http (default: stdio)
|
||||
-m, --model Claude model to use (default: claude-3-7-sonnet-20250219)
|
||||
-o, --output Output file for report (default: print to stdout)
|
||||
|
||||
stdio options:
|
||||
-c, --command Command to run MCP server (e.g., python, node)
|
||||
-a, --args Arguments for the command (e.g., server.py)
|
||||
-e, --env Environment variables in KEY=VALUE format
|
||||
|
||||
sse/http options:
|
||||
-u, --url MCP server URL
|
||||
-H, --header HTTP headers in 'Key: Value' format
|
||||
```
|
||||
|
||||
## Output
|
||||
|
||||
The evaluation script generates a detailed report including:
|
||||
|
||||
- **Summary Statistics**:
|
||||
- Accuracy (correct/total)
|
||||
- Average task duration
|
||||
- Average tool calls per task
|
||||
- Total tool calls
|
||||
|
||||
- **Per-Task Results**:
|
||||
- Prompt and expected response
|
||||
- Actual response from the agent
|
||||
- Whether the answer was correct (✅/❌)
|
||||
- Duration and tool call details
|
||||
- Agent's summary of its approach
|
||||
- Agent's feedback on the tools
|
||||
|
||||
### Save Report to File
|
||||
|
||||
```bash
|
||||
python scripts/evaluation.py \
|
||||
-t stdio \
|
||||
-c python \
|
||||
-a my_server.py \
|
||||
-o evaluation_report.md \
|
||||
evaluation.xml
|
||||
```
|
||||
|
||||
## Complete Example Workflow
|
||||
|
||||
Here's a complete example of creating and running an evaluation:
|
||||
|
||||
1. **Create your evaluation file** (`my_evaluation.xml`):
|
||||
|
||||
```xml
|
||||
<evaluation>
|
||||
<qa_pair>
|
||||
<question>Find the user who created the most issues in January 2024. What is their username?</question>
|
||||
<answer>alice_developer</answer>
|
||||
</qa_pair>
|
||||
<qa_pair>
|
||||
<question>Among all pull requests merged in Q1 2024, which repository had the highest number? Provide the repository name.</question>
|
||||
<answer>backend-api</answer>
|
||||
</qa_pair>
|
||||
<qa_pair>
|
||||
<question>Find the project that was completed in December 2023 and had the longest duration from start to finish. How many days did it take?</question>
|
||||
<answer>127</answer>
|
||||
</qa_pair>
|
||||
</evaluation>
|
||||
```
|
||||
|
||||
2. **Install dependencies**:
|
||||
|
||||
```bash
|
||||
pip install -r scripts/requirements.txt
|
||||
export ANTHROPIC_API_KEY=your_api_key
|
||||
```
|
||||
|
||||
3. **Run evaluation**:
|
||||
|
||||
```bash
|
||||
python scripts/evaluation.py \
|
||||
-t stdio \
|
||||
-c python \
|
||||
-a github_mcp_server.py \
|
||||
-e GITHUB_TOKEN=ghp_xxx \
|
||||
-o github_eval_report.md \
|
||||
my_evaluation.xml
|
||||
```
|
||||
|
||||
4. **Review the report** in `github_eval_report.md` to:
|
||||
- See which questions passed/failed
|
||||
- Read the agent's feedback on your tools
|
||||
- Identify areas for improvement
|
||||
- Iterate on your MCP server design
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Connection Errors
|
||||
|
||||
If you get connection errors:
|
||||
- **STDIO**: Verify the command and arguments are correct
|
||||
- **SSE/HTTP**: Check the URL is accessible and headers are correct
|
||||
- Ensure any required API keys are set in environment variables or headers
|
||||
|
||||
### Low Accuracy
|
||||
|
||||
If many evaluations fail:
|
||||
- Review the agent's feedback for each task
|
||||
- Check if tool descriptions are clear and comprehensive
|
||||
- Verify input parameters are well-documented
|
||||
- Consider whether tools return too much or too little data
|
||||
- Ensure error messages are actionable
|
||||
|
||||
### Timeout Issues
|
||||
|
||||
If tasks are timing out:
|
||||
- Use a more capable model (e.g., `claude-3-7-sonnet-20250219`)
|
||||
- Check if tools are returning too much data
|
||||
- Verify pagination is working correctly
|
||||
- Consider simplifying complex questions
|
||||
@@ -0,0 +1,249 @@
|
||||
# MCP Server Best Practices
|
||||
|
||||
## Quick Reference
|
||||
|
||||
### Server Naming
|
||||
- **Python**: `{service}_mcp` (e.g., `slack_mcp`)
|
||||
- **Node/TypeScript**: `{service}-mcp-server` (e.g., `slack-mcp-server`)
|
||||
|
||||
### Tool Naming
|
||||
- Use snake_case with service prefix
|
||||
- Format: `{service}_{action}_{resource}`
|
||||
- Example: `slack_send_message`, `github_create_issue`
|
||||
|
||||
### Response Formats
|
||||
- Support both JSON and Markdown formats
|
||||
- JSON for programmatic processing
|
||||
- Markdown for human readability
|
||||
|
||||
### Pagination
|
||||
- Always respect `limit` parameter
|
||||
- Return `has_more`, `next_offset`, `total_count`
|
||||
- Default to 20-50 items
|
||||
|
||||
### Transport
|
||||
- **Streamable HTTP**: For remote servers, multi-client scenarios
|
||||
- **stdio**: For local integrations, command-line tools
|
||||
- Avoid SSE (deprecated in favor of streamable HTTP)
|
||||
|
||||
---
|
||||
|
||||
## Server Naming Conventions
|
||||
|
||||
Follow these standardized naming patterns:
|
||||
|
||||
**Python**: Use format `{service}_mcp` (lowercase with underscores)
|
||||
- Examples: `slack_mcp`, `github_mcp`, `jira_mcp`
|
||||
|
||||
**Node/TypeScript**: Use format `{service}-mcp-server` (lowercase with hyphens)
|
||||
- Examples: `slack-mcp-server`, `github-mcp-server`, `jira-mcp-server`
|
||||
|
||||
The name should be general, descriptive of the service being integrated, easy to infer from the task description, and without version numbers.
|
||||
|
||||
---
|
||||
|
||||
## Tool Naming and Design
|
||||
|
||||
### Tool Naming
|
||||
|
||||
1. **Use snake_case**: `search_users`, `create_project`, `get_channel_info`
|
||||
2. **Include service prefix**: Anticipate that your MCP server may be used alongside other MCP servers
|
||||
- Use `slack_send_message` instead of just `send_message`
|
||||
- Use `github_create_issue` instead of just `create_issue`
|
||||
3. **Be action-oriented**: Start with verbs (get, list, search, create, etc.)
|
||||
4. **Be specific**: Avoid generic names that could conflict with other servers
|
||||
|
||||
### Tool Design
|
||||
|
||||
- Tool descriptions must narrowly and unambiguously describe functionality
|
||||
- Descriptions must precisely match actual functionality
|
||||
- Provide tool annotations (readOnlyHint, destructiveHint, idempotentHint, openWorldHint)
|
||||
- Keep tool operations focused and atomic
|
||||
|
||||
---
|
||||
|
||||
## Response Formats
|
||||
|
||||
All tools that return data should support multiple formats:
|
||||
|
||||
### JSON Format (`response_format="json"`)
|
||||
- Machine-readable structured data
|
||||
- Include all available fields and metadata
|
||||
- Consistent field names and types
|
||||
- Use for programmatic processing
|
||||
|
||||
### Markdown Format (`response_format="markdown"`, typically default)
|
||||
- Human-readable formatted text
|
||||
- Use headers, lists, and formatting for clarity
|
||||
- Convert timestamps to human-readable format
|
||||
- Show display names with IDs in parentheses
|
||||
- Omit verbose metadata
|
||||
|
||||
---
|
||||
|
||||
## Pagination
|
||||
|
||||
For tools that list resources:
|
||||
|
||||
- **Always respect the `limit` parameter**
|
||||
- **Implement pagination**: Use `offset` or cursor-based pagination
|
||||
- **Return pagination metadata**: Include `has_more`, `next_offset`/`next_cursor`, `total_count`
|
||||
- **Never load all results into memory**: Especially important for large datasets
|
||||
- **Default to reasonable limits**: 20-50 items is typical
|
||||
|
||||
Example pagination response:
|
||||
```json
|
||||
{
|
||||
"total": 150,
|
||||
"count": 20,
|
||||
"offset": 0,
|
||||
"items": [...],
|
||||
"has_more": true,
|
||||
"next_offset": 20
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Transport Options
|
||||
|
||||
### Streamable HTTP
|
||||
|
||||
**Best for**: Remote servers, web services, multi-client scenarios
|
||||
|
||||
**Characteristics**:
|
||||
- Bidirectional communication over HTTP
|
||||
- Supports multiple simultaneous clients
|
||||
- Can be deployed as a web service
|
||||
- Enables server-to-client notifications
|
||||
|
||||
**Use when**:
|
||||
- Serving multiple clients simultaneously
|
||||
- Deploying as a cloud service
|
||||
- Integration with web applications
|
||||
|
||||
### stdio
|
||||
|
||||
**Best for**: Local integrations, command-line tools
|
||||
|
||||
**Characteristics**:
|
||||
- Standard input/output stream communication
|
||||
- Simple setup, no network configuration needed
|
||||
- Runs as a subprocess of the client
|
||||
|
||||
**Use when**:
|
||||
- Building tools for local development environments
|
||||
- Integrating with desktop applications
|
||||
- Single-user, single-session scenarios
|
||||
|
||||
**Note**: stdio servers should NOT log to stdout (use stderr for logging)
|
||||
|
||||
### Transport Selection
|
||||
|
||||
| Criterion | stdio | Streamable HTTP |
|
||||
|-----------|-------|-----------------|
|
||||
| **Deployment** | Local | Remote |
|
||||
| **Clients** | Single | Multiple |
|
||||
| **Complexity** | Low | Medium |
|
||||
| **Real-time** | No | Yes |
|
||||
|
||||
---
|
||||
|
||||
## Security Best Practices
|
||||
|
||||
### Authentication and Authorization
|
||||
|
||||
**OAuth 2.1**:
|
||||
- Use secure OAuth 2.1 with certificates from recognized authorities
|
||||
- Validate access tokens before processing requests
|
||||
- Only accept tokens specifically intended for your server
|
||||
|
||||
**API Keys**:
|
||||
- Store API keys in environment variables, never in code
|
||||
- Validate keys on server startup
|
||||
- Provide clear error messages when authentication fails
|
||||
|
||||
### Input Validation
|
||||
|
||||
- Sanitize file paths to prevent directory traversal
|
||||
- Validate URLs and external identifiers
|
||||
- Check parameter sizes and ranges
|
||||
- Prevent command injection in system calls
|
||||
- Use schema validation (Pydantic/Zod) for all inputs
|
||||
|
||||
### Error Handling
|
||||
|
||||
- Don't expose internal errors to clients
|
||||
- Log security-relevant errors server-side
|
||||
- Provide helpful but not revealing error messages
|
||||
- Clean up resources after errors
|
||||
|
||||
### DNS Rebinding Protection
|
||||
|
||||
For streamable HTTP servers running locally:
|
||||
- Enable DNS rebinding protection
|
||||
- Validate the `Origin` header on all incoming connections
|
||||
- Bind to `127.0.0.1` rather than `0.0.0.0`
|
||||
|
||||
---
|
||||
|
||||
## Tool Annotations
|
||||
|
||||
Provide annotations to help clients understand tool behavior:
|
||||
|
||||
| Annotation | Type | Default | Description |
|
||||
|-----------|------|---------|-------------|
|
||||
| `readOnlyHint` | boolean | false | Tool does not modify its environment |
|
||||
| `destructiveHint` | boolean | true | Tool may perform destructive updates |
|
||||
| `idempotentHint` | boolean | false | Repeated calls with same args have no additional effect |
|
||||
| `openWorldHint` | boolean | true | Tool interacts with external entities |
|
||||
|
||||
**Important**: Annotations are hints, not security guarantees. Clients should not make security-critical decisions based solely on annotations.
|
||||
|
||||
---
|
||||
|
||||
## Error Handling
|
||||
|
||||
- Use standard JSON-RPC error codes
|
||||
- Report tool errors within result objects (not protocol-level errors)
|
||||
- Provide helpful, specific error messages with suggested next steps
|
||||
- Don't expose internal implementation details
|
||||
- Clean up resources properly on errors
|
||||
|
||||
Example error handling:
|
||||
```typescript
|
||||
try {
|
||||
const result = performOperation();
|
||||
return { content: [{ type: "text", text: result }] };
|
||||
} catch (error) {
|
||||
return {
|
||||
isError: true,
|
||||
content: [{
|
||||
type: "text",
|
||||
text: `Error: ${error.message}. Try using filter='active_only' to reduce results.`
|
||||
}]
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Testing Requirements
|
||||
|
||||
Comprehensive testing should cover:
|
||||
|
||||
- **Functional testing**: Verify correct execution with valid/invalid inputs
|
||||
- **Integration testing**: Test interaction with external systems
|
||||
- **Security testing**: Validate auth, input sanitization, rate limiting
|
||||
- **Performance testing**: Check behavior under load, timeouts
|
||||
- **Error handling**: Ensure proper error reporting and cleanup
|
||||
|
||||
---
|
||||
|
||||
## Documentation Requirements
|
||||
|
||||
- Provide clear documentation of all tools and capabilities
|
||||
- Include working examples (at least 3 per major feature)
|
||||
- Document security considerations
|
||||
- Specify required permissions and access levels
|
||||
- Document rate limits and performance characteristics
|
||||
@@ -0,0 +1,970 @@
|
||||
# Node/TypeScript MCP Server Implementation Guide
|
||||
|
||||
## Overview
|
||||
|
||||
This document provides Node/TypeScript-specific best practices and examples for implementing MCP servers using the MCP TypeScript SDK. It covers project structure, server setup, tool registration patterns, input validation with Zod, error handling, and complete working examples.
|
||||
|
||||
---
|
||||
|
||||
## Quick Reference
|
||||
|
||||
### Key Imports
|
||||
```typescript
|
||||
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
||||
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
||||
import express from "express";
|
||||
import { z } from "zod";
|
||||
```
|
||||
|
||||
### Server Initialization
|
||||
```typescript
|
||||
const server = new McpServer({
|
||||
name: "service-mcp-server",
|
||||
version: "1.0.0"
|
||||
});
|
||||
```
|
||||
|
||||
### Tool Registration Pattern
|
||||
```typescript
|
||||
server.registerTool(
|
||||
"tool_name",
|
||||
{
|
||||
title: "Tool Display Name",
|
||||
description: "What the tool does",
|
||||
inputSchema: { param: z.string() },
|
||||
outputSchema: { result: z.string() }
|
||||
},
|
||||
async ({ param }) => {
|
||||
const output = { result: `Processed: ${param}` };
|
||||
return {
|
||||
content: [{ type: "text", text: JSON.stringify(output) }],
|
||||
structuredContent: output // Modern pattern for structured data
|
||||
};
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## MCP TypeScript SDK
|
||||
|
||||
The official MCP TypeScript SDK provides:
|
||||
- `McpServer` class for server initialization
|
||||
- `registerTool` method for tool registration
|
||||
- Zod schema integration for runtime input validation
|
||||
- Type-safe tool handler implementations
|
||||
|
||||
**IMPORTANT - Use Modern APIs Only:**
|
||||
- **DO use**: `server.registerTool()`, `server.registerResource()`, `server.registerPrompt()`
|
||||
- **DO NOT use**: Old deprecated APIs such as `server.tool()`, `server.setRequestHandler(ListToolsRequestSchema, ...)`, or manual handler registration
|
||||
- The `register*` methods provide better type safety, automatic schema handling, and are the recommended approach
|
||||
|
||||
See the MCP SDK documentation in the references for complete details.
|
||||
|
||||
## Server Naming Convention
|
||||
|
||||
Node/TypeScript MCP servers must follow this naming pattern:
|
||||
- **Format**: `{service}-mcp-server` (lowercase with hyphens)
|
||||
- **Examples**: `github-mcp-server`, `jira-mcp-server`, `stripe-mcp-server`
|
||||
|
||||
The name should be:
|
||||
- General (not tied to specific features)
|
||||
- Descriptive of the service/API being integrated
|
||||
- Easy to infer from the task description
|
||||
- Without version numbers or dates
|
||||
|
||||
## Project Structure
|
||||
|
||||
Create the following structure for Node/TypeScript MCP servers:
|
||||
|
||||
```
|
||||
{service}-mcp-server/
|
||||
├── package.json
|
||||
├── tsconfig.json
|
||||
├── README.md
|
||||
├── src/
|
||||
│ ├── index.ts # Main entry point with McpServer initialization
|
||||
│ ├── types.ts # TypeScript type definitions and interfaces
|
||||
│ ├── tools/ # Tool implementations (one file per domain)
|
||||
│ ├── services/ # API clients and shared utilities
|
||||
│ ├── schemas/ # Zod validation schemas
|
||||
│ └── constants.ts # Shared constants (API_URL, CHARACTER_LIMIT, etc.)
|
||||
└── dist/ # Built JavaScript files (entry point: dist/index.js)
|
||||
```
|
||||
|
||||
## Tool Implementation
|
||||
|
||||
### Tool Naming
|
||||
|
||||
Use snake_case for tool names (e.g., "search_users", "create_project", "get_channel_info") with clear, action-oriented names.
|
||||
|
||||
**Avoid Naming Conflicts**: Include the service context to prevent overlaps:
|
||||
- Use "slack_send_message" instead of just "send_message"
|
||||
- Use "github_create_issue" instead of just "create_issue"
|
||||
- Use "asana_list_tasks" instead of just "list_tasks"
|
||||
|
||||
### Tool Structure
|
||||
|
||||
Tools are registered using the `registerTool` method with the following requirements:
|
||||
- Use Zod schemas for runtime input validation and type safety
|
||||
- The `description` field must be explicitly provided - JSDoc comments are NOT automatically extracted
|
||||
- Explicitly provide `title`, `description`, `inputSchema`, and `annotations`
|
||||
- The `inputSchema` must be a Zod schema object (not a JSON schema)
|
||||
- Type all parameters and return values explicitly
|
||||
|
||||
```typescript
|
||||
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import { z } from "zod";
|
||||
|
||||
const server = new McpServer({
|
||||
name: "example-mcp",
|
||||
version: "1.0.0"
|
||||
});
|
||||
|
||||
// Zod schema for input validation
|
||||
const UserSearchInputSchema = z.object({
|
||||
query: z.string()
|
||||
.min(2, "Query must be at least 2 characters")
|
||||
.max(200, "Query must not exceed 200 characters")
|
||||
.describe("Search string to match against names/emails"),
|
||||
limit: z.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(100)
|
||||
.default(20)
|
||||
.describe("Maximum results to return"),
|
||||
offset: z.number()
|
||||
.int()
|
||||
.min(0)
|
||||
.default(0)
|
||||
.describe("Number of results to skip for pagination"),
|
||||
response_format: z.nativeEnum(ResponseFormat)
|
||||
.default(ResponseFormat.MARKDOWN)
|
||||
.describe("Output format: 'markdown' for human-readable or 'json' for machine-readable")
|
||||
}).strict();
|
||||
|
||||
// Type definition from Zod schema
|
||||
type UserSearchInput = z.infer<typeof UserSearchInputSchema>;
|
||||
|
||||
server.registerTool(
|
||||
"example_search_users",
|
||||
{
|
||||
title: "Search Example Users",
|
||||
description: `Search for users in the Example system by name, email, or team.
|
||||
|
||||
This tool searches across all user profiles in the Example platform, supporting partial matches and various search filters. It does NOT create or modify users, only searches existing ones.
|
||||
|
||||
Args:
|
||||
- query (string): Search string to match against names/emails
|
||||
- limit (number): Maximum results to return, between 1-100 (default: 20)
|
||||
- offset (number): Number of results to skip for pagination (default: 0)
|
||||
- response_format ('markdown' | 'json'): Output format (default: 'markdown')
|
||||
|
||||
Returns:
|
||||
For JSON format: Structured data with schema:
|
||||
{
|
||||
"total": number, // Total number of matches found
|
||||
"count": number, // Number of results in this response
|
||||
"offset": number, // Current pagination offset
|
||||
"users": [
|
||||
{
|
||||
"id": string, // User ID (e.g., "U123456789")
|
||||
"name": string, // Full name (e.g., "John Doe")
|
||||
"email": string, // Email address
|
||||
"team": string, // Team name (optional)
|
||||
"active": boolean // Whether user is active
|
||||
}
|
||||
],
|
||||
"has_more": boolean, // Whether more results are available
|
||||
"next_offset": number // Offset for next page (if has_more is true)
|
||||
}
|
||||
|
||||
Examples:
|
||||
- Use when: "Find all marketing team members" -> params with query="team:marketing"
|
||||
- Use when: "Search for John's account" -> params with query="john"
|
||||
- Don't use when: You need to create a user (use example_create_user instead)
|
||||
|
||||
Error Handling:
|
||||
- Returns "Error: Rate limit exceeded" if too many requests (429 status)
|
||||
- Returns "No users found matching '<query>'" if search returns empty`,
|
||||
inputSchema: UserSearchInputSchema,
|
||||
annotations: {
|
||||
readOnlyHint: true,
|
||||
destructiveHint: false,
|
||||
idempotentHint: true,
|
||||
openWorldHint: true
|
||||
}
|
||||
},
|
||||
async (params: UserSearchInput) => {
|
||||
try {
|
||||
// Input validation is handled by Zod schema
|
||||
// Make API request using validated parameters
|
||||
const data = await makeApiRequest<any>(
|
||||
"users/search",
|
||||
"GET",
|
||||
undefined,
|
||||
{
|
||||
q: params.query,
|
||||
limit: params.limit,
|
||||
offset: params.offset
|
||||
}
|
||||
);
|
||||
|
||||
const users = data.users || [];
|
||||
const total = data.total || 0;
|
||||
|
||||
if (!users.length) {
|
||||
return {
|
||||
content: [{
|
||||
type: "text",
|
||||
text: `No users found matching '${params.query}'`
|
||||
}]
|
||||
};
|
||||
}
|
||||
|
||||
// Prepare structured output
|
||||
const output = {
|
||||
total,
|
||||
count: users.length,
|
||||
offset: params.offset,
|
||||
users: users.map((user: any) => ({
|
||||
id: user.id,
|
||||
name: user.name,
|
||||
email: user.email,
|
||||
...(user.team ? { team: user.team } : {}),
|
||||
active: user.active ?? true
|
||||
})),
|
||||
has_more: total > params.offset + users.length,
|
||||
...(total > params.offset + users.length ? {
|
||||
next_offset: params.offset + users.length
|
||||
} : {})
|
||||
};
|
||||
|
||||
// Format text representation based on requested format
|
||||
let textContent: string;
|
||||
if (params.response_format === ResponseFormat.MARKDOWN) {
|
||||
const lines = [`# User Search Results: '${params.query}'`, "",
|
||||
`Found ${total} users (showing ${users.length})`, ""];
|
||||
for (const user of users) {
|
||||
lines.push(`## ${user.name} (${user.id})`);
|
||||
lines.push(`- **Email**: ${user.email}`);
|
||||
if (user.team) lines.push(`- **Team**: ${user.team}`);
|
||||
lines.push("");
|
||||
}
|
||||
textContent = lines.join("\n");
|
||||
} else {
|
||||
textContent = JSON.stringify(output, null, 2);
|
||||
}
|
||||
|
||||
return {
|
||||
content: [{ type: "text", text: textContent }],
|
||||
structuredContent: output // Modern pattern for structured data
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
content: [{
|
||||
type: "text",
|
||||
text: handleApiError(error)
|
||||
}]
|
||||
};
|
||||
}
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
## Zod Schemas for Input Validation
|
||||
|
||||
Zod provides runtime type validation:
|
||||
|
||||
```typescript
|
||||
import { z } from "zod";
|
||||
|
||||
// Basic schema with validation
|
||||
const CreateUserSchema = z.object({
|
||||
name: z.string()
|
||||
.min(1, "Name is required")
|
||||
.max(100, "Name must not exceed 100 characters"),
|
||||
email: z.string()
|
||||
.email("Invalid email format"),
|
||||
age: z.number()
|
||||
.int("Age must be a whole number")
|
||||
.min(0, "Age cannot be negative")
|
||||
.max(150, "Age cannot be greater than 150")
|
||||
}).strict(); // Use .strict() to forbid extra fields
|
||||
|
||||
// Enums
|
||||
enum ResponseFormat {
|
||||
MARKDOWN = "markdown",
|
||||
JSON = "json"
|
||||
}
|
||||
|
||||
const SearchSchema = z.object({
|
||||
response_format: z.nativeEnum(ResponseFormat)
|
||||
.default(ResponseFormat.MARKDOWN)
|
||||
.describe("Output format")
|
||||
});
|
||||
|
||||
// Optional fields with defaults
|
||||
const PaginationSchema = z.object({
|
||||
limit: z.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(100)
|
||||
.default(20)
|
||||
.describe("Maximum results to return"),
|
||||
offset: z.number()
|
||||
.int()
|
||||
.min(0)
|
||||
.default(0)
|
||||
.describe("Number of results to skip")
|
||||
});
|
||||
```
|
||||
|
||||
## Response Format Options
|
||||
|
||||
Support multiple output formats for flexibility:
|
||||
|
||||
```typescript
|
||||
enum ResponseFormat {
|
||||
MARKDOWN = "markdown",
|
||||
JSON = "json"
|
||||
}
|
||||
|
||||
const inputSchema = z.object({
|
||||
query: z.string(),
|
||||
response_format: z.nativeEnum(ResponseFormat)
|
||||
.default(ResponseFormat.MARKDOWN)
|
||||
.describe("Output format: 'markdown' for human-readable or 'json' for machine-readable")
|
||||
});
|
||||
```
|
||||
|
||||
**Markdown format**:
|
||||
- Use headers, lists, and formatting for clarity
|
||||
- Convert timestamps to human-readable format
|
||||
- Show display names with IDs in parentheses
|
||||
- Omit verbose metadata
|
||||
- Group related information logically
|
||||
|
||||
**JSON format**:
|
||||
- Return complete, structured data suitable for programmatic processing
|
||||
- Include all available fields and metadata
|
||||
- Use consistent field names and types
|
||||
|
||||
## Pagination Implementation
|
||||
|
||||
For tools that list resources:
|
||||
|
||||
```typescript
|
||||
const ListSchema = z.object({
|
||||
limit: z.number().int().min(1).max(100).default(20),
|
||||
offset: z.number().int().min(0).default(0)
|
||||
});
|
||||
|
||||
async function listItems(params: z.infer<typeof ListSchema>) {
|
||||
const data = await apiRequest(params.limit, params.offset);
|
||||
|
||||
const response = {
|
||||
total: data.total,
|
||||
count: data.items.length,
|
||||
offset: params.offset,
|
||||
items: data.items,
|
||||
has_more: data.total > params.offset + data.items.length,
|
||||
next_offset: data.total > params.offset + data.items.length
|
||||
? params.offset + data.items.length
|
||||
: undefined
|
||||
};
|
||||
|
||||
return JSON.stringify(response, null, 2);
|
||||
}
|
||||
```
|
||||
|
||||
## Character Limits and Truncation
|
||||
|
||||
Add a CHARACTER_LIMIT constant to prevent overwhelming responses:
|
||||
|
||||
```typescript
|
||||
// At module level in constants.ts
|
||||
export const CHARACTER_LIMIT = 25000; // Maximum response size in characters
|
||||
|
||||
async function searchTool(params: SearchInput) {
|
||||
let result = generateResponse(data);
|
||||
|
||||
// Check character limit and truncate if needed
|
||||
if (result.length > CHARACTER_LIMIT) {
|
||||
const truncatedData = data.slice(0, Math.max(1, data.length / 2));
|
||||
response.data = truncatedData;
|
||||
response.truncated = true;
|
||||
response.truncation_message =
|
||||
`Response truncated from ${data.length} to ${truncatedData.length} items. ` +
|
||||
`Use 'offset' parameter or add filters to see more results.`;
|
||||
result = JSON.stringify(response, null, 2);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
Provide clear, actionable error messages:
|
||||
|
||||
```typescript
|
||||
import axios, { AxiosError } from "axios";
|
||||
|
||||
function handleApiError(error: unknown): string {
|
||||
if (error instanceof AxiosError) {
|
||||
if (error.response) {
|
||||
switch (error.response.status) {
|
||||
case 404:
|
||||
return "Error: Resource not found. Please check the ID is correct.";
|
||||
case 403:
|
||||
return "Error: Permission denied. You don't have access to this resource.";
|
||||
case 429:
|
||||
return "Error: Rate limit exceeded. Please wait before making more requests.";
|
||||
default:
|
||||
return `Error: API request failed with status ${error.response.status}`;
|
||||
}
|
||||
} else if (error.code === "ECONNABORTED") {
|
||||
return "Error: Request timed out. Please try again.";
|
||||
}
|
||||
}
|
||||
return `Error: Unexpected error occurred: ${error instanceof Error ? error.message : String(error)}`;
|
||||
}
|
||||
```
|
||||
|
||||
## Shared Utilities
|
||||
|
||||
Extract common functionality into reusable functions:
|
||||
|
||||
```typescript
|
||||
// Shared API request function
|
||||
async function makeApiRequest<T>(
|
||||
endpoint: string,
|
||||
method: "GET" | "POST" | "PUT" | "DELETE" = "GET",
|
||||
data?: any,
|
||||
params?: any
|
||||
): Promise<T> {
|
||||
try {
|
||||
const response = await axios({
|
||||
method,
|
||||
url: `${API_BASE_URL}/${endpoint}`,
|
||||
data,
|
||||
params,
|
||||
timeout: 30000,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json"
|
||||
}
|
||||
});
|
||||
return response.data;
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Async/Await Best Practices
|
||||
|
||||
Always use async/await for network requests and I/O operations:
|
||||
|
||||
```typescript
|
||||
// Good: Async network request
|
||||
async function fetchData(resourceId: string): Promise<ResourceData> {
|
||||
const response = await axios.get(`${API_URL}/resource/${resourceId}`);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
// Bad: Promise chains
|
||||
function fetchData(resourceId: string): Promise<ResourceData> {
|
||||
return axios.get(`${API_URL}/resource/${resourceId}`)
|
||||
.then(response => response.data); // Harder to read and maintain
|
||||
}
|
||||
```
|
||||
|
||||
## TypeScript Best Practices
|
||||
|
||||
1. **Use Strict TypeScript**: Enable strict mode in tsconfig.json
|
||||
2. **Define Interfaces**: Create clear interface definitions for all data structures
|
||||
3. **Avoid `any`**: Use proper types or `unknown` instead of `any`
|
||||
4. **Zod for Runtime Validation**: Use Zod schemas to validate external data
|
||||
5. **Type Guards**: Create type guard functions for complex type checking
|
||||
6. **Error Handling**: Always use try-catch with proper error type checking
|
||||
7. **Null Safety**: Use optional chaining (`?.`) and nullish coalescing (`??`)
|
||||
|
||||
```typescript
|
||||
// Good: Type-safe with Zod and interfaces
|
||||
interface UserResponse {
|
||||
id: string;
|
||||
name: string;
|
||||
email: string;
|
||||
team?: string;
|
||||
active: boolean;
|
||||
}
|
||||
|
||||
const UserSchema = z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
email: z.string().email(),
|
||||
team: z.string().optional(),
|
||||
active: z.boolean()
|
||||
});
|
||||
|
||||
type User = z.infer<typeof UserSchema>;
|
||||
|
||||
async function getUser(id: string): Promise<User> {
|
||||
const data = await apiCall(`/users/${id}`);
|
||||
return UserSchema.parse(data); // Runtime validation
|
||||
}
|
||||
|
||||
// Bad: Using any
|
||||
async function getUser(id: string): Promise<any> {
|
||||
return await apiCall(`/users/${id}`); // No type safety
|
||||
}
|
||||
```
|
||||
|
||||
## Package Configuration
|
||||
|
||||
### package.json
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "{service}-mcp-server",
|
||||
"version": "1.0.0",
|
||||
"description": "MCP server for {Service} API integration",
|
||||
"type": "module",
|
||||
"main": "dist/index.js",
|
||||
"scripts": {
|
||||
"start": "node dist/index.js",
|
||||
"dev": "tsx watch src/index.ts",
|
||||
"build": "tsc",
|
||||
"clean": "rm -rf dist"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"dependencies": {
|
||||
"@modelcontextprotocol/sdk": "^1.6.1",
|
||||
"axios": "^1.7.9",
|
||||
"zod": "^3.23.8"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.10.0",
|
||||
"tsx": "^4.19.2",
|
||||
"typescript": "^5.7.2"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### tsconfig.json
|
||||
|
||||
```json
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "Node16",
|
||||
"moduleResolution": "Node16",
|
||||
"lib": ["ES2022"],
|
||||
"outDir": "./dist",
|
||||
"rootDir": "./src",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"declaration": true,
|
||||
"declarationMap": true,
|
||||
"sourceMap": true,
|
||||
"allowSyntheticDefaultImports": true
|
||||
},
|
||||
"include": ["src/**/*"],
|
||||
"exclude": ["node_modules", "dist"]
|
||||
}
|
||||
```
|
||||
|
||||
## Complete Example
|
||||
|
||||
```typescript
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* MCP Server for Example Service.
|
||||
*
|
||||
* This server provides tools to interact with Example API, including user search,
|
||||
* project management, and data export capabilities.
|
||||
*/
|
||||
|
||||
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
||||
import { z } from "zod";
|
||||
import axios, { AxiosError } from "axios";
|
||||
|
||||
// Constants
|
||||
const API_BASE_URL = "https://api.example.com/v1";
|
||||
const CHARACTER_LIMIT = 25000;
|
||||
|
||||
// Enums
|
||||
enum ResponseFormat {
|
||||
MARKDOWN = "markdown",
|
||||
JSON = "json"
|
||||
}
|
||||
|
||||
// Zod schemas
|
||||
const UserSearchInputSchema = z.object({
|
||||
query: z.string()
|
||||
.min(2, "Query must be at least 2 characters")
|
||||
.max(200, "Query must not exceed 200 characters")
|
||||
.describe("Search string to match against names/emails"),
|
||||
limit: z.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(100)
|
||||
.default(20)
|
||||
.describe("Maximum results to return"),
|
||||
offset: z.number()
|
||||
.int()
|
||||
.min(0)
|
||||
.default(0)
|
||||
.describe("Number of results to skip for pagination"),
|
||||
response_format: z.nativeEnum(ResponseFormat)
|
||||
.default(ResponseFormat.MARKDOWN)
|
||||
.describe("Output format: 'markdown' for human-readable or 'json' for machine-readable")
|
||||
}).strict();
|
||||
|
||||
type UserSearchInput = z.infer<typeof UserSearchInputSchema>;
|
||||
|
||||
// Shared utility functions
|
||||
async function makeApiRequest<T>(
|
||||
endpoint: string,
|
||||
method: "GET" | "POST" | "PUT" | "DELETE" = "GET",
|
||||
data?: any,
|
||||
params?: any
|
||||
): Promise<T> {
|
||||
try {
|
||||
const response = await axios({
|
||||
method,
|
||||
url: `${API_BASE_URL}/${endpoint}`,
|
||||
data,
|
||||
params,
|
||||
timeout: 30000,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json"
|
||||
}
|
||||
});
|
||||
return response.data;
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function handleApiError(error: unknown): string {
|
||||
if (error instanceof AxiosError) {
|
||||
if (error.response) {
|
||||
switch (error.response.status) {
|
||||
case 404:
|
||||
return "Error: Resource not found. Please check the ID is correct.";
|
||||
case 403:
|
||||
return "Error: Permission denied. You don't have access to this resource.";
|
||||
case 429:
|
||||
return "Error: Rate limit exceeded. Please wait before making more requests.";
|
||||
default:
|
||||
return `Error: API request failed with status ${error.response.status}`;
|
||||
}
|
||||
} else if (error.code === "ECONNABORTED") {
|
||||
return "Error: Request timed out. Please try again.";
|
||||
}
|
||||
}
|
||||
return `Error: Unexpected error occurred: ${error instanceof Error ? error.message : String(error)}`;
|
||||
}
|
||||
|
||||
// Create MCP server instance
|
||||
const server = new McpServer({
|
||||
name: "example-mcp",
|
||||
version: "1.0.0"
|
||||
});
|
||||
|
||||
// Register tools
|
||||
server.registerTool(
|
||||
"example_search_users",
|
||||
{
|
||||
title: "Search Example Users",
|
||||
description: `[Full description as shown above]`,
|
||||
inputSchema: UserSearchInputSchema,
|
||||
annotations: {
|
||||
readOnlyHint: true,
|
||||
destructiveHint: false,
|
||||
idempotentHint: true,
|
||||
openWorldHint: true
|
||||
}
|
||||
},
|
||||
async (params: UserSearchInput) => {
|
||||
// Implementation as shown above
|
||||
}
|
||||
);
|
||||
|
||||
// Main function
|
||||
// For stdio (local):
|
||||
async function runStdio() {
|
||||
if (!process.env.EXAMPLE_API_KEY) {
|
||||
console.error("ERROR: EXAMPLE_API_KEY environment variable is required");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const transport = new StdioServerTransport();
|
||||
await server.connect(transport);
|
||||
console.error("MCP server running via stdio");
|
||||
}
|
||||
|
||||
// For streamable HTTP (remote):
|
||||
async function runHTTP() {
|
||||
if (!process.env.EXAMPLE_API_KEY) {
|
||||
console.error("ERROR: EXAMPLE_API_KEY environment variable is required");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
|
||||
app.post('/mcp', async (req, res) => {
|
||||
const transport = new StreamableHTTPServerTransport({
|
||||
sessionIdGenerator: undefined,
|
||||
enableJsonResponse: true
|
||||
});
|
||||
res.on('close', () => transport.close());
|
||||
await server.connect(transport);
|
||||
await transport.handleRequest(req, res, req.body);
|
||||
});
|
||||
|
||||
const port = parseInt(process.env.PORT || '3000');
|
||||
app.listen(port, () => {
|
||||
console.error(`MCP server running on http://localhost:${port}/mcp`);
|
||||
});
|
||||
}
|
||||
|
||||
// Choose transport based on environment
|
||||
const transport = process.env.TRANSPORT || 'stdio';
|
||||
if (transport === 'http') {
|
||||
runHTTP().catch(error => {
|
||||
console.error("Server error:", error);
|
||||
process.exit(1);
|
||||
});
|
||||
} else {
|
||||
runStdio().catch(error => {
|
||||
console.error("Server error:", error);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Advanced MCP Features
|
||||
|
||||
### Resource Registration
|
||||
|
||||
Expose data as resources for efficient, URI-based access:
|
||||
|
||||
```typescript
|
||||
import { ResourceTemplate } from "@modelcontextprotocol/sdk/types.js";
|
||||
|
||||
// Register a resource with URI template
|
||||
server.registerResource(
|
||||
{
|
||||
uri: "file://documents/{name}",
|
||||
name: "Document Resource",
|
||||
description: "Access documents by name",
|
||||
mimeType: "text/plain"
|
||||
},
|
||||
async (uri: string) => {
|
||||
// Extract parameter from URI
|
||||
const match = uri.match(/^file:\/\/documents\/(.+)$/);
|
||||
if (!match) {
|
||||
throw new Error("Invalid URI format");
|
||||
}
|
||||
|
||||
const documentName = match[1];
|
||||
const content = await loadDocument(documentName);
|
||||
|
||||
return {
|
||||
contents: [{
|
||||
uri,
|
||||
mimeType: "text/plain",
|
||||
text: content
|
||||
}]
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
// List available resources dynamically
|
||||
server.registerResourceList(async () => {
|
||||
const documents = await getAvailableDocuments();
|
||||
return {
|
||||
resources: documents.map(doc => ({
|
||||
uri: `file://documents/${doc.name}`,
|
||||
name: doc.name,
|
||||
mimeType: "text/plain",
|
||||
description: doc.description
|
||||
}))
|
||||
};
|
||||
});
|
||||
```
|
||||
|
||||
**When to use Resources vs Tools:**
|
||||
- **Resources**: For data access with simple URI-based parameters
|
||||
- **Tools**: For complex operations requiring validation and business logic
|
||||
- **Resources**: When data is relatively static or template-based
|
||||
- **Tools**: When operations have side effects or complex workflows
|
||||
|
||||
### Transport Options
|
||||
|
||||
The TypeScript SDK supports two main transport mechanisms:
|
||||
|
||||
#### Streamable HTTP (Recommended for Remote Servers)
|
||||
|
||||
```typescript
|
||||
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
||||
import express from "express";
|
||||
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
|
||||
app.post('/mcp', async (req, res) => {
|
||||
// Create new transport for each request (stateless, prevents request ID collisions)
|
||||
const transport = new StreamableHTTPServerTransport({
|
||||
sessionIdGenerator: undefined,
|
||||
enableJsonResponse: true
|
||||
});
|
||||
|
||||
res.on('close', () => transport.close());
|
||||
|
||||
await server.connect(transport);
|
||||
await transport.handleRequest(req, res, req.body);
|
||||
});
|
||||
|
||||
app.listen(3000);
|
||||
```
|
||||
|
||||
#### stdio (For Local Integrations)
|
||||
|
||||
```typescript
|
||||
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
||||
|
||||
const transport = new StdioServerTransport();
|
||||
await server.connect(transport);
|
||||
```
|
||||
|
||||
**Transport selection:**
|
||||
- **Streamable HTTP**: Web services, remote access, multiple clients
|
||||
- **stdio**: Command-line tools, local development, subprocess integration
|
||||
|
||||
### Notification Support
|
||||
|
||||
Notify clients when server state changes:
|
||||
|
||||
```typescript
|
||||
// Notify when tools list changes
|
||||
server.notification({
|
||||
method: "notifications/tools/list_changed"
|
||||
});
|
||||
|
||||
// Notify when resources change
|
||||
server.notification({
|
||||
method: "notifications/resources/list_changed"
|
||||
});
|
||||
```
|
||||
|
||||
Use notifications sparingly - only when server capabilities genuinely change.
|
||||
|
||||
---
|
||||
|
||||
## Code Best Practices
|
||||
|
||||
### Code Composability and Reusability
|
||||
|
||||
Your implementation MUST prioritize composability and code reuse:
|
||||
|
||||
1. **Extract Common Functionality**:
|
||||
- Create reusable helper functions for operations used across multiple tools
|
||||
- Build shared API clients for HTTP requests instead of duplicating code
|
||||
- Centralize error handling logic in utility functions
|
||||
- Extract business logic into dedicated functions that can be composed
|
||||
- Extract shared markdown or JSON field selection & formatting functionality
|
||||
|
||||
2. **Avoid Duplication**:
|
||||
- NEVER copy-paste similar code between tools
|
||||
- If you find yourself writing similar logic twice, extract it into a function
|
||||
- Common operations like pagination, filtering, field selection, and formatting should be shared
|
||||
- Authentication/authorization logic should be centralized
|
||||
|
||||
## Building and Running
|
||||
|
||||
Always build your TypeScript code before running:
|
||||
|
||||
```bash
|
||||
# Build the project
|
||||
npm run build
|
||||
|
||||
# Run the server
|
||||
npm start
|
||||
|
||||
# Development with auto-reload
|
||||
npm run dev
|
||||
```
|
||||
|
||||
Always ensure `npm run build` completes successfully before considering the implementation complete.
|
||||
|
||||
## Quality Checklist
|
||||
|
||||
Before finalizing your Node/TypeScript MCP server implementation, ensure:
|
||||
|
||||
### Strategic Design
|
||||
- [ ] Tools enable complete workflows, not just API endpoint wrappers
|
||||
- [ ] Tool names reflect natural task subdivisions
|
||||
- [ ] Response formats optimize for agent context efficiency
|
||||
- [ ] Human-readable identifiers used where appropriate
|
||||
- [ ] Error messages guide agents toward correct usage
|
||||
|
||||
### Implementation Quality
|
||||
- [ ] FOCUSED IMPLEMENTATION: Most important and valuable tools implemented
|
||||
- [ ] All tools registered using `registerTool` with complete configuration
|
||||
- [ ] All tools include `title`, `description`, `inputSchema`, and `annotations`
|
||||
- [ ] Annotations correctly set (readOnlyHint, destructiveHint, idempotentHint, openWorldHint)
|
||||
- [ ] All tools use Zod schemas for runtime input validation with `.strict()` enforcement
|
||||
- [ ] All Zod schemas have proper constraints and descriptive error messages
|
||||
- [ ] All tools have comprehensive descriptions with explicit input/output types
|
||||
- [ ] Descriptions include return value examples and complete schema documentation
|
||||
- [ ] Error messages are clear, actionable, and educational
|
||||
|
||||
### TypeScript Quality
|
||||
- [ ] TypeScript interfaces are defined for all data structures
|
||||
- [ ] Strict TypeScript is enabled in tsconfig.json
|
||||
- [ ] No use of `any` type - use `unknown` or proper types instead
|
||||
- [ ] All async functions have explicit Promise<T> return types
|
||||
- [ ] Error handling uses proper type guards (e.g., `axios.isAxiosError`, `z.ZodError`)
|
||||
|
||||
### Advanced Features (where applicable)
|
||||
- [ ] Resources registered for appropriate data endpoints
|
||||
- [ ] Appropriate transport configured (stdio or streamable HTTP)
|
||||
- [ ] Notifications implemented for dynamic server capabilities
|
||||
- [ ] Type-safe with SDK interfaces
|
||||
|
||||
### Project Configuration
|
||||
- [ ] Package.json includes all necessary dependencies
|
||||
- [ ] Build script produces working JavaScript in dist/ directory
|
||||
- [ ] Main entry point is properly configured as dist/index.js
|
||||
- [ ] Server name follows format: `{service}-mcp-server`
|
||||
- [ ] tsconfig.json properly configured with strict mode
|
||||
|
||||
### Code Quality
|
||||
- [ ] Pagination is properly implemented where applicable
|
||||
- [ ] Large responses check CHARACTER_LIMIT constant and truncate with clear messages
|
||||
- [ ] Filtering options are provided for potentially large result sets
|
||||
- [ ] All network operations handle timeouts and connection errors gracefully
|
||||
- [ ] Common functionality is extracted into reusable functions
|
||||
- [ ] Return types are consistent across similar operations
|
||||
|
||||
### Testing and Build
|
||||
- [ ] `npm run build` completes successfully without errors
|
||||
- [ ] dist/index.js created and executable
|
||||
- [ ] Server runs: `node dist/index.js --help`
|
||||
- [ ] All imports resolve correctly
|
||||
- [ ] Sample tool calls work as expected
|
||||
@@ -0,0 +1,719 @@
|
||||
# Python MCP Server Implementation Guide
|
||||
|
||||
## Overview
|
||||
|
||||
This document provides Python-specific best practices and examples for implementing MCP servers using the MCP Python SDK. It covers server setup, tool registration patterns, input validation with Pydantic, error handling, and complete working examples.
|
||||
|
||||
---
|
||||
|
||||
## Quick Reference
|
||||
|
||||
### Key Imports
|
||||
```python
|
||||
from mcp.server.fastmcp import FastMCP
|
||||
from pydantic import BaseModel, Field, field_validator, ConfigDict
|
||||
from typing import Optional, List, Dict, Any
|
||||
from enum import Enum
|
||||
import httpx
|
||||
```
|
||||
|
||||
### Server Initialization
|
||||
```python
|
||||
mcp = FastMCP("service_mcp")
|
||||
```
|
||||
|
||||
### Tool Registration Pattern
|
||||
```python
|
||||
@mcp.tool(name="tool_name", annotations={...})
|
||||
async def tool_function(params: InputModel) -> str:
|
||||
# Implementation
|
||||
pass
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## MCP Python SDK and FastMCP
|
||||
|
||||
The official MCP Python SDK provides FastMCP, a high-level framework for building MCP servers. It provides:
|
||||
- Automatic description and inputSchema generation from function signatures and docstrings
|
||||
- Pydantic model integration for input validation
|
||||
- Decorator-based tool registration with `@mcp.tool`
|
||||
|
||||
**For complete SDK documentation, use WebFetch to load:**
|
||||
`https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/main/README.md`
|
||||
|
||||
## Server Naming Convention
|
||||
|
||||
Python MCP servers must follow this naming pattern:
|
||||
- **Format**: `{service}_mcp` (lowercase with underscores)
|
||||
- **Examples**: `github_mcp`, `jira_mcp`, `stripe_mcp`
|
||||
|
||||
The name should be:
|
||||
- General (not tied to specific features)
|
||||
- Descriptive of the service/API being integrated
|
||||
- Easy to infer from the task description
|
||||
- Without version numbers or dates
|
||||
|
||||
## Tool Implementation
|
||||
|
||||
### Tool Naming
|
||||
|
||||
Use snake_case for tool names (e.g., "search_users", "create_project", "get_channel_info") with clear, action-oriented names.
|
||||
|
||||
**Avoid Naming Conflicts**: Include the service context to prevent overlaps:
|
||||
- Use "slack_send_message" instead of just "send_message"
|
||||
- Use "github_create_issue" instead of just "create_issue"
|
||||
- Use "asana_list_tasks" instead of just "list_tasks"
|
||||
|
||||
### Tool Structure with FastMCP
|
||||
|
||||
Tools are defined using the `@mcp.tool` decorator with Pydantic models for input validation:
|
||||
|
||||
```python
|
||||
from pydantic import BaseModel, Field, ConfigDict
|
||||
from mcp.server.fastmcp import FastMCP
|
||||
|
||||
# Initialize the MCP server
|
||||
mcp = FastMCP("example_mcp")
|
||||
|
||||
# Define Pydantic model for input validation
|
||||
class ServiceToolInput(BaseModel):
|
||||
'''Input model for service tool operation.'''
|
||||
model_config = ConfigDict(
|
||||
str_strip_whitespace=True, # Auto-strip whitespace from strings
|
||||
validate_assignment=True, # Validate on assignment
|
||||
extra='forbid' # Forbid extra fields
|
||||
)
|
||||
|
||||
param1: str = Field(..., description="First parameter description (e.g., 'user123', 'project-abc')", min_length=1, max_length=100)
|
||||
param2: Optional[int] = Field(default=None, description="Optional integer parameter with constraints", ge=0, le=1000)
|
||||
tags: Optional[List[str]] = Field(default_factory=list, description="List of tags to apply", max_items=10)
|
||||
|
||||
@mcp.tool(
|
||||
name="service_tool_name",
|
||||
annotations={
|
||||
"title": "Human-Readable Tool Title",
|
||||
"readOnlyHint": True, # Tool does not modify environment
|
||||
"destructiveHint": False, # Tool does not perform destructive operations
|
||||
"idempotentHint": True, # Repeated calls have no additional effect
|
||||
"openWorldHint": False # Tool does not interact with external entities
|
||||
}
|
||||
)
|
||||
async def service_tool_name(params: ServiceToolInput) -> str:
|
||||
'''Tool description automatically becomes the 'description' field.
|
||||
|
||||
This tool performs a specific operation on the service. It validates all inputs
|
||||
using the ServiceToolInput Pydantic model before processing.
|
||||
|
||||
Args:
|
||||
params (ServiceToolInput): Validated input parameters containing:
|
||||
- param1 (str): First parameter description
|
||||
- param2 (Optional[int]): Optional parameter with default
|
||||
- tags (Optional[List[str]]): List of tags
|
||||
|
||||
Returns:
|
||||
str: JSON-formatted response containing operation results
|
||||
'''
|
||||
# Implementation here
|
||||
pass
|
||||
```
|
||||
|
||||
## Pydantic v2 Key Features
|
||||
|
||||
- Use `model_config` instead of nested `Config` class
|
||||
- Use `field_validator` instead of deprecated `validator`
|
||||
- Use `model_dump()` instead of deprecated `dict()`
|
||||
- Validators require `@classmethod` decorator
|
||||
- Type hints are required for validator methods
|
||||
|
||||
```python
|
||||
from pydantic import BaseModel, Field, field_validator, ConfigDict
|
||||
|
||||
class CreateUserInput(BaseModel):
|
||||
model_config = ConfigDict(
|
||||
str_strip_whitespace=True,
|
||||
validate_assignment=True
|
||||
)
|
||||
|
||||
name: str = Field(..., description="User's full name", min_length=1, max_length=100)
|
||||
email: str = Field(..., description="User's email address", pattern=r'^[\w\.-]+@[\w\.-]+\.\w+$')
|
||||
age: int = Field(..., description="User's age", ge=0, le=150)
|
||||
|
||||
@field_validator('email')
|
||||
@classmethod
|
||||
def validate_email(cls, v: str) -> str:
|
||||
if not v.strip():
|
||||
raise ValueError("Email cannot be empty")
|
||||
return v.lower()
|
||||
```
|
||||
|
||||
## Response Format Options
|
||||
|
||||
Support multiple output formats for flexibility:
|
||||
|
||||
```python
|
||||
from enum import Enum
|
||||
|
||||
class ResponseFormat(str, Enum):
|
||||
'''Output format for tool responses.'''
|
||||
MARKDOWN = "markdown"
|
||||
JSON = "json"
|
||||
|
||||
class UserSearchInput(BaseModel):
|
||||
query: str = Field(..., description="Search query")
|
||||
response_format: ResponseFormat = Field(
|
||||
default=ResponseFormat.MARKDOWN,
|
||||
description="Output format: 'markdown' for human-readable or 'json' for machine-readable"
|
||||
)
|
||||
```
|
||||
|
||||
**Markdown format**:
|
||||
- Use headers, lists, and formatting for clarity
|
||||
- Convert timestamps to human-readable format (e.g., "2024-01-15 10:30:00 UTC" instead of epoch)
|
||||
- Show display names with IDs in parentheses (e.g., "@john.doe (U123456)")
|
||||
- Omit verbose metadata (e.g., show only one profile image URL, not all sizes)
|
||||
- Group related information logically
|
||||
|
||||
**JSON format**:
|
||||
- Return complete, structured data suitable for programmatic processing
|
||||
- Include all available fields and metadata
|
||||
- Use consistent field names and types
|
||||
|
||||
## Pagination Implementation
|
||||
|
||||
For tools that list resources:
|
||||
|
||||
```python
|
||||
class ListInput(BaseModel):
|
||||
limit: Optional[int] = Field(default=20, description="Maximum results to return", ge=1, le=100)
|
||||
offset: Optional[int] = Field(default=0, description="Number of results to skip for pagination", ge=0)
|
||||
|
||||
async def list_items(params: ListInput) -> str:
|
||||
# Make API request with pagination
|
||||
data = await api_request(limit=params.limit, offset=params.offset)
|
||||
|
||||
# Return pagination info
|
||||
response = {
|
||||
"total": data["total"],
|
||||
"count": len(data["items"]),
|
||||
"offset": params.offset,
|
||||
"items": data["items"],
|
||||
"has_more": data["total"] > params.offset + len(data["items"]),
|
||||
"next_offset": params.offset + len(data["items"]) if data["total"] > params.offset + len(data["items"]) else None
|
||||
}
|
||||
return json.dumps(response, indent=2)
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
Provide clear, actionable error messages:
|
||||
|
||||
```python
|
||||
def _handle_api_error(e: Exception) -> str:
|
||||
'''Consistent error formatting across all tools.'''
|
||||
if isinstance(e, httpx.HTTPStatusError):
|
||||
if e.response.status_code == 404:
|
||||
return "Error: Resource not found. Please check the ID is correct."
|
||||
elif e.response.status_code == 403:
|
||||
return "Error: Permission denied. You don't have access to this resource."
|
||||
elif e.response.status_code == 429:
|
||||
return "Error: Rate limit exceeded. Please wait before making more requests."
|
||||
return f"Error: API request failed with status {e.response.status_code}"
|
||||
elif isinstance(e, httpx.TimeoutException):
|
||||
return "Error: Request timed out. Please try again."
|
||||
return f"Error: Unexpected error occurred: {type(e).__name__}"
|
||||
```
|
||||
|
||||
## Shared Utilities
|
||||
|
||||
Extract common functionality into reusable functions:
|
||||
|
||||
```python
|
||||
# Shared API request function
|
||||
async def _make_api_request(endpoint: str, method: str = "GET", **kwargs) -> dict:
|
||||
'''Reusable function for all API calls.'''
|
||||
async with httpx.AsyncClient() as client:
|
||||
response = await client.request(
|
||||
method,
|
||||
f"{API_BASE_URL}/{endpoint}",
|
||||
timeout=30.0,
|
||||
**kwargs
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
```
|
||||
|
||||
## Async/Await Best Practices
|
||||
|
||||
Always use async/await for network requests and I/O operations:
|
||||
|
||||
```python
|
||||
# Good: Async network request
|
||||
async def fetch_data(resource_id: str) -> dict:
|
||||
async with httpx.AsyncClient() as client:
|
||||
response = await client.get(f"{API_URL}/resource/{resource_id}")
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
# Bad: Synchronous request
|
||||
def fetch_data(resource_id: str) -> dict:
|
||||
response = requests.get(f"{API_URL}/resource/{resource_id}") # Blocks
|
||||
return response.json()
|
||||
```
|
||||
|
||||
## Type Hints
|
||||
|
||||
Use type hints throughout:
|
||||
|
||||
```python
|
||||
from typing import Optional, List, Dict, Any
|
||||
|
||||
async def get_user(user_id: str) -> Dict[str, Any]:
|
||||
data = await fetch_user(user_id)
|
||||
return {"id": data["id"], "name": data["name"]}
|
||||
```
|
||||
|
||||
## Tool Docstrings
|
||||
|
||||
Every tool must have comprehensive docstrings with explicit type information:
|
||||
|
||||
```python
|
||||
async def search_users(params: UserSearchInput) -> str:
|
||||
'''
|
||||
Search for users in the Example system by name, email, or team.
|
||||
|
||||
This tool searches across all user profiles in the Example platform,
|
||||
supporting partial matches and various search filters. It does NOT
|
||||
create or modify users, only searches existing ones.
|
||||
|
||||
Args:
|
||||
params (UserSearchInput): Validated input parameters containing:
|
||||
- query (str): Search string to match against names/emails (e.g., "john", "@example.com", "team:marketing")
|
||||
- limit (Optional[int]): Maximum results to return, between 1-100 (default: 20)
|
||||
- offset (Optional[int]): Number of results to skip for pagination (default: 0)
|
||||
|
||||
Returns:
|
||||
str: JSON-formatted string containing search results with the following schema:
|
||||
|
||||
Success response:
|
||||
{
|
||||
"total": int, # Total number of matches found
|
||||
"count": int, # Number of results in this response
|
||||
"offset": int, # Current pagination offset
|
||||
"users": [
|
||||
{
|
||||
"id": str, # User ID (e.g., "U123456789")
|
||||
"name": str, # Full name (e.g., "John Doe")
|
||||
"email": str, # Email address (e.g., "john@example.com")
|
||||
"team": str # Team name (e.g., "Marketing") - optional
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
Error response:
|
||||
"Error: <error message>" or "No users found matching '<query>'"
|
||||
|
||||
Examples:
|
||||
- Use when: "Find all marketing team members" -> params with query="team:marketing"
|
||||
- Use when: "Search for John's account" -> params with query="john"
|
||||
- Don't use when: You need to create a user (use example_create_user instead)
|
||||
- Don't use when: You have a user ID and need full details (use example_get_user instead)
|
||||
|
||||
Error Handling:
|
||||
- Input validation errors are handled by Pydantic model
|
||||
- Returns "Error: Rate limit exceeded" if too many requests (429 status)
|
||||
- Returns "Error: Invalid API authentication" if API key is invalid (401 status)
|
||||
- Returns formatted list of results or "No users found matching 'query'"
|
||||
'''
|
||||
```
|
||||
|
||||
## Complete Example
|
||||
|
||||
See below for a complete Python MCP server example:
|
||||
|
||||
```python
|
||||
#!/usr/bin/env python3
|
||||
'''
|
||||
MCP Server for Example Service.
|
||||
|
||||
This server provides tools to interact with Example API, including user search,
|
||||
project management, and data export capabilities.
|
||||
'''
|
||||
|
||||
from typing import Optional, List, Dict, Any
|
||||
from enum import Enum
|
||||
import httpx
|
||||
from pydantic import BaseModel, Field, field_validator, ConfigDict
|
||||
from mcp.server.fastmcp import FastMCP
|
||||
|
||||
# Initialize the MCP server
|
||||
mcp = FastMCP("example_mcp")
|
||||
|
||||
# Constants
|
||||
API_BASE_URL = "https://api.example.com/v1"
|
||||
|
||||
# Enums
|
||||
class ResponseFormat(str, Enum):
|
||||
'''Output format for tool responses.'''
|
||||
MARKDOWN = "markdown"
|
||||
JSON = "json"
|
||||
|
||||
# Pydantic Models for Input Validation
|
||||
class UserSearchInput(BaseModel):
|
||||
'''Input model for user search operations.'''
|
||||
model_config = ConfigDict(
|
||||
str_strip_whitespace=True,
|
||||
validate_assignment=True
|
||||
)
|
||||
|
||||
query: str = Field(..., description="Search string to match against names/emails", min_length=2, max_length=200)
|
||||
limit: Optional[int] = Field(default=20, description="Maximum results to return", ge=1, le=100)
|
||||
offset: Optional[int] = Field(default=0, description="Number of results to skip for pagination", ge=0)
|
||||
response_format: ResponseFormat = Field(default=ResponseFormat.MARKDOWN, description="Output format")
|
||||
|
||||
@field_validator('query')
|
||||
@classmethod
|
||||
def validate_query(cls, v: str) -> str:
|
||||
if not v.strip():
|
||||
raise ValueError("Query cannot be empty or whitespace only")
|
||||
return v.strip()
|
||||
|
||||
# Shared utility functions
|
||||
async def _make_api_request(endpoint: str, method: str = "GET", **kwargs) -> dict:
|
||||
'''Reusable function for all API calls.'''
|
||||
async with httpx.AsyncClient() as client:
|
||||
response = await client.request(
|
||||
method,
|
||||
f"{API_BASE_URL}/{endpoint}",
|
||||
timeout=30.0,
|
||||
**kwargs
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
def _handle_api_error(e: Exception) -> str:
|
||||
'''Consistent error formatting across all tools.'''
|
||||
if isinstance(e, httpx.HTTPStatusError):
|
||||
if e.response.status_code == 404:
|
||||
return "Error: Resource not found. Please check the ID is correct."
|
||||
elif e.response.status_code == 403:
|
||||
return "Error: Permission denied. You don't have access to this resource."
|
||||
elif e.response.status_code == 429:
|
||||
return "Error: Rate limit exceeded. Please wait before making more requests."
|
||||
return f"Error: API request failed with status {e.response.status_code}"
|
||||
elif isinstance(e, httpx.TimeoutException):
|
||||
return "Error: Request timed out. Please try again."
|
||||
return f"Error: Unexpected error occurred: {type(e).__name__}"
|
||||
|
||||
# Tool definitions
|
||||
@mcp.tool(
|
||||
name="example_search_users",
|
||||
annotations={
|
||||
"title": "Search Example Users",
|
||||
"readOnlyHint": True,
|
||||
"destructiveHint": False,
|
||||
"idempotentHint": True,
|
||||
"openWorldHint": True
|
||||
}
|
||||
)
|
||||
async def example_search_users(params: UserSearchInput) -> str:
|
||||
'''Search for users in the Example system by name, email, or team.
|
||||
|
||||
[Full docstring as shown above]
|
||||
'''
|
||||
try:
|
||||
# Make API request using validated parameters
|
||||
data = await _make_api_request(
|
||||
"users/search",
|
||||
params={
|
||||
"q": params.query,
|
||||
"limit": params.limit,
|
||||
"offset": params.offset
|
||||
}
|
||||
)
|
||||
|
||||
users = data.get("users", [])
|
||||
total = data.get("total", 0)
|
||||
|
||||
if not users:
|
||||
return f"No users found matching '{params.query}'"
|
||||
|
||||
# Format response based on requested format
|
||||
if params.response_format == ResponseFormat.MARKDOWN:
|
||||
lines = [f"# User Search Results: '{params.query}'", ""]
|
||||
lines.append(f"Found {total} users (showing {len(users)})")
|
||||
lines.append("")
|
||||
|
||||
for user in users:
|
||||
lines.append(f"## {user['name']} ({user['id']})")
|
||||
lines.append(f"- **Email**: {user['email']}")
|
||||
if user.get('team'):
|
||||
lines.append(f"- **Team**: {user['team']}")
|
||||
lines.append("")
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
else:
|
||||
# Machine-readable JSON format
|
||||
import json
|
||||
response = {
|
||||
"total": total,
|
||||
"count": len(users),
|
||||
"offset": params.offset,
|
||||
"users": users
|
||||
}
|
||||
return json.dumps(response, indent=2)
|
||||
|
||||
except Exception as e:
|
||||
return _handle_api_error(e)
|
||||
|
||||
if __name__ == "__main__":
|
||||
mcp.run()
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Advanced FastMCP Features
|
||||
|
||||
### Context Parameter Injection
|
||||
|
||||
FastMCP can automatically inject a `Context` parameter into tools for advanced capabilities like logging, progress reporting, resource reading, and user interaction:
|
||||
|
||||
```python
|
||||
from mcp.server.fastmcp import FastMCP, Context
|
||||
|
||||
mcp = FastMCP("example_mcp")
|
||||
|
||||
@mcp.tool()
|
||||
async def advanced_search(query: str, ctx: Context) -> str:
|
||||
'''Advanced tool with context access for logging and progress.'''
|
||||
|
||||
# Report progress for long operations
|
||||
await ctx.report_progress(0.25, "Starting search...")
|
||||
|
||||
# Log information for debugging
|
||||
await ctx.log_info("Processing query", {"query": query, "timestamp": datetime.now()})
|
||||
|
||||
# Perform search
|
||||
results = await search_api(query)
|
||||
await ctx.report_progress(0.75, "Formatting results...")
|
||||
|
||||
# Access server configuration
|
||||
server_name = ctx.fastmcp.name
|
||||
|
||||
return format_results(results)
|
||||
|
||||
@mcp.tool()
|
||||
async def interactive_tool(resource_id: str, ctx: Context) -> str:
|
||||
'''Tool that can request additional input from users.'''
|
||||
|
||||
# Request sensitive information when needed
|
||||
api_key = await ctx.elicit(
|
||||
prompt="Please provide your API key:",
|
||||
input_type="password"
|
||||
)
|
||||
|
||||
# Use the provided key
|
||||
return await api_call(resource_id, api_key)
|
||||
```
|
||||
|
||||
**Context capabilities:**
|
||||
- `ctx.report_progress(progress, message)` - Report progress for long operations
|
||||
- `ctx.log_info(message, data)` / `ctx.log_error()` / `ctx.log_debug()` - Logging
|
||||
- `ctx.elicit(prompt, input_type)` - Request input from users
|
||||
- `ctx.fastmcp.name` - Access server configuration
|
||||
- `ctx.read_resource(uri)` - Read MCP resources
|
||||
|
||||
### Resource Registration
|
||||
|
||||
Expose data as resources for efficient, template-based access:
|
||||
|
||||
```python
|
||||
@mcp.resource("file://documents/{name}")
|
||||
async def get_document(name: str) -> str:
|
||||
'''Expose documents as MCP resources.
|
||||
|
||||
Resources are useful for static or semi-static data that doesn't
|
||||
require complex parameters. They use URI templates for flexible access.
|
||||
'''
|
||||
document_path = f"./docs/{name}"
|
||||
with open(document_path, "r") as f:
|
||||
return f.read()
|
||||
|
||||
@mcp.resource("config://settings/{key}")
|
||||
async def get_setting(key: str, ctx: Context) -> str:
|
||||
'''Expose configuration as resources with context.'''
|
||||
settings = await load_settings()
|
||||
return json.dumps(settings.get(key, {}))
|
||||
```
|
||||
|
||||
**When to use Resources vs Tools:**
|
||||
- **Resources**: For data access with simple parameters (URI templates)
|
||||
- **Tools**: For complex operations with validation and business logic
|
||||
|
||||
### Structured Output Types
|
||||
|
||||
FastMCP supports multiple return types beyond strings:
|
||||
|
||||
```python
|
||||
from typing import TypedDict
|
||||
from dataclasses import dataclass
|
||||
from pydantic import BaseModel
|
||||
|
||||
# TypedDict for structured returns
|
||||
class UserData(TypedDict):
|
||||
id: str
|
||||
name: str
|
||||
email: str
|
||||
|
||||
@mcp.tool()
|
||||
async def get_user_typed(user_id: str) -> UserData:
|
||||
'''Returns structured data - FastMCP handles serialization.'''
|
||||
return {"id": user_id, "name": "John Doe", "email": "john@example.com"}
|
||||
|
||||
# Pydantic models for complex validation
|
||||
class DetailedUser(BaseModel):
|
||||
id: str
|
||||
name: str
|
||||
email: str
|
||||
created_at: datetime
|
||||
metadata: Dict[str, Any]
|
||||
|
||||
@mcp.tool()
|
||||
async def get_user_detailed(user_id: str) -> DetailedUser:
|
||||
'''Returns Pydantic model - automatically generates schema.'''
|
||||
user = await fetch_user(user_id)
|
||||
return DetailedUser(**user)
|
||||
```
|
||||
|
||||
### Lifespan Management
|
||||
|
||||
Initialize resources that persist across requests:
|
||||
|
||||
```python
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
@asynccontextmanager
|
||||
async def app_lifespan():
|
||||
'''Manage resources that live for the server's lifetime.'''
|
||||
# Initialize connections, load config, etc.
|
||||
db = await connect_to_database()
|
||||
config = load_configuration()
|
||||
|
||||
# Make available to all tools
|
||||
yield {"db": db, "config": config}
|
||||
|
||||
# Cleanup on shutdown
|
||||
await db.close()
|
||||
|
||||
mcp = FastMCP("example_mcp", lifespan=app_lifespan)
|
||||
|
||||
@mcp.tool()
|
||||
async def query_data(query: str, ctx: Context) -> str:
|
||||
'''Access lifespan resources through context.'''
|
||||
db = ctx.request_context.lifespan_state["db"]
|
||||
results = await db.query(query)
|
||||
return format_results(results)
|
||||
```
|
||||
|
||||
### Transport Options
|
||||
|
||||
FastMCP supports two main transport mechanisms:
|
||||
|
||||
```python
|
||||
# stdio transport (for local tools) - default
|
||||
if __name__ == "__main__":
|
||||
mcp.run()
|
||||
|
||||
# Streamable HTTP transport (for remote servers)
|
||||
if __name__ == "__main__":
|
||||
mcp.run(transport="streamable_http", port=8000)
|
||||
```
|
||||
|
||||
**Transport selection:**
|
||||
- **stdio**: Command-line tools, local integrations, subprocess execution
|
||||
- **Streamable HTTP**: Web services, remote access, multiple clients
|
||||
|
||||
---
|
||||
|
||||
## Code Best Practices
|
||||
|
||||
### Code Composability and Reusability
|
||||
|
||||
Your implementation MUST prioritize composability and code reuse:
|
||||
|
||||
1. **Extract Common Functionality**:
|
||||
- Create reusable helper functions for operations used across multiple tools
|
||||
- Build shared API clients for HTTP requests instead of duplicating code
|
||||
- Centralize error handling logic in utility functions
|
||||
- Extract business logic into dedicated functions that can be composed
|
||||
- Extract shared markdown or JSON field selection & formatting functionality
|
||||
|
||||
2. **Avoid Duplication**:
|
||||
- NEVER copy-paste similar code between tools
|
||||
- If you find yourself writing similar logic twice, extract it into a function
|
||||
- Common operations like pagination, filtering, field selection, and formatting should be shared
|
||||
- Authentication/authorization logic should be centralized
|
||||
|
||||
### Python-Specific Best Practices
|
||||
|
||||
1. **Use Type Hints**: Always include type annotations for function parameters and return values
|
||||
2. **Pydantic Models**: Define clear Pydantic models for all input validation
|
||||
3. **Avoid Manual Validation**: Let Pydantic handle input validation with constraints
|
||||
4. **Proper Imports**: Group imports (standard library, third-party, local)
|
||||
5. **Error Handling**: Use specific exception types (httpx.HTTPStatusError, not generic Exception)
|
||||
6. **Async Context Managers**: Use `async with` for resources that need cleanup
|
||||
7. **Constants**: Define module-level constants in UPPER_CASE
|
||||
|
||||
## Quality Checklist
|
||||
|
||||
Before finalizing your Python MCP server implementation, ensure:
|
||||
|
||||
### Strategic Design
|
||||
- [ ] Tools enable complete workflows, not just API endpoint wrappers
|
||||
- [ ] Tool names reflect natural task subdivisions
|
||||
- [ ] Response formats optimize for agent context efficiency
|
||||
- [ ] Human-readable identifiers used where appropriate
|
||||
- [ ] Error messages guide agents toward correct usage
|
||||
|
||||
### Implementation Quality
|
||||
- [ ] FOCUSED IMPLEMENTATION: Most important and valuable tools implemented
|
||||
- [ ] All tools have descriptive names and documentation
|
||||
- [ ] Return types are consistent across similar operations
|
||||
- [ ] Error handling is implemented for all external calls
|
||||
- [ ] Server name follows format: `{service}_mcp`
|
||||
- [ ] All network operations use async/await
|
||||
- [ ] Common functionality is extracted into reusable functions
|
||||
- [ ] Error messages are clear, actionable, and educational
|
||||
- [ ] Outputs are properly validated and formatted
|
||||
|
||||
### Tool Configuration
|
||||
- [ ] All tools implement 'name' and 'annotations' in the decorator
|
||||
- [ ] Annotations correctly set (readOnlyHint, destructiveHint, idempotentHint, openWorldHint)
|
||||
- [ ] All tools use Pydantic BaseModel for input validation with Field() definitions
|
||||
- [ ] All Pydantic Fields have explicit types and descriptions with constraints
|
||||
- [ ] All tools have comprehensive docstrings with explicit input/output types
|
||||
- [ ] Docstrings include complete schema structure for dict/JSON returns
|
||||
- [ ] Pydantic models handle input validation (no manual validation needed)
|
||||
|
||||
### Advanced Features (where applicable)
|
||||
- [ ] Context injection used for logging, progress, or elicitation
|
||||
- [ ] Resources registered for appropriate data endpoints
|
||||
- [ ] Lifespan management implemented for persistent connections
|
||||
- [ ] Structured output types used (TypedDict, Pydantic models)
|
||||
- [ ] Appropriate transport configured (stdio or streamable HTTP)
|
||||
|
||||
### Code Quality
|
||||
- [ ] File includes proper imports including Pydantic imports
|
||||
- [ ] Pagination is properly implemented where applicable
|
||||
- [ ] Filtering options are provided for potentially large result sets
|
||||
- [ ] All async functions are properly defined with `async def`
|
||||
- [ ] HTTP client usage follows async patterns with proper context managers
|
||||
- [ ] Type hints are used throughout the code
|
||||
- [ ] Constants are defined at module level in UPPER_CASE
|
||||
|
||||
### Testing
|
||||
- [ ] Server runs successfully: `python your_server.py --help`
|
||||
- [ ] All imports resolve correctly
|
||||
- [ ] Sample tool calls work as expected
|
||||
- [ ] Error scenarios handled gracefully
|
||||
@@ -0,0 +1,151 @@
|
||||
"""Lightweight connection handling for MCP servers."""
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from contextlib import AsyncExitStack
|
||||
from typing import Any
|
||||
|
||||
from mcp import ClientSession, StdioServerParameters
|
||||
from mcp.client.sse import sse_client
|
||||
from mcp.client.stdio import stdio_client
|
||||
from mcp.client.streamable_http import streamablehttp_client
|
||||
|
||||
|
||||
class MCPConnection(ABC):
|
||||
"""Base class for MCP server connections."""
|
||||
|
||||
def __init__(self):
|
||||
self.session = None
|
||||
self._stack = None
|
||||
|
||||
@abstractmethod
|
||||
def _create_context(self):
|
||||
"""Create the connection context based on connection type."""
|
||||
|
||||
async def __aenter__(self):
|
||||
"""Initialize MCP server connection."""
|
||||
self._stack = AsyncExitStack()
|
||||
await self._stack.__aenter__()
|
||||
|
||||
try:
|
||||
ctx = self._create_context()
|
||||
result = await self._stack.enter_async_context(ctx)
|
||||
|
||||
if len(result) == 2:
|
||||
read, write = result
|
||||
elif len(result) == 3:
|
||||
read, write, _ = result
|
||||
else:
|
||||
raise ValueError(f"Unexpected context result: {result}")
|
||||
|
||||
session_ctx = ClientSession(read, write)
|
||||
self.session = await self._stack.enter_async_context(session_ctx)
|
||||
await self.session.initialize()
|
||||
return self
|
||||
except BaseException:
|
||||
await self._stack.__aexit__(None, None, None)
|
||||
raise
|
||||
|
||||
async def __aexit__(self, exc_type, exc_val, exc_tb):
|
||||
"""Clean up MCP server connection resources."""
|
||||
if self._stack:
|
||||
await self._stack.__aexit__(exc_type, exc_val, exc_tb)
|
||||
self.session = None
|
||||
self._stack = None
|
||||
|
||||
async def list_tools(self) -> list[dict[str, Any]]:
|
||||
"""Retrieve available tools from the MCP server."""
|
||||
response = await self.session.list_tools()
|
||||
return [
|
||||
{
|
||||
"name": tool.name,
|
||||
"description": tool.description,
|
||||
"input_schema": tool.inputSchema,
|
||||
}
|
||||
for tool in response.tools
|
||||
]
|
||||
|
||||
async def call_tool(self, tool_name: str, arguments: dict[str, Any]) -> Any:
|
||||
"""Call a tool on the MCP server with provided arguments."""
|
||||
result = await self.session.call_tool(tool_name, arguments=arguments)
|
||||
return result.content
|
||||
|
||||
|
||||
class MCPConnectionStdio(MCPConnection):
|
||||
"""MCP connection using standard input/output."""
|
||||
|
||||
def __init__(self, command: str, args: list[str] = None, env: dict[str, str] = None):
|
||||
super().__init__()
|
||||
self.command = command
|
||||
self.args = args or []
|
||||
self.env = env
|
||||
|
||||
def _create_context(self):
|
||||
return stdio_client(
|
||||
StdioServerParameters(command=self.command, args=self.args, env=self.env)
|
||||
)
|
||||
|
||||
|
||||
class MCPConnectionSSE(MCPConnection):
|
||||
"""MCP connection using Server-Sent Events."""
|
||||
|
||||
def __init__(self, url: str, headers: dict[str, str] = None):
|
||||
super().__init__()
|
||||
self.url = url
|
||||
self.headers = headers or {}
|
||||
|
||||
def _create_context(self):
|
||||
return sse_client(url=self.url, headers=self.headers)
|
||||
|
||||
|
||||
class MCPConnectionHTTP(MCPConnection):
|
||||
"""MCP connection using Streamable HTTP."""
|
||||
|
||||
def __init__(self, url: str, headers: dict[str, str] = None):
|
||||
super().__init__()
|
||||
self.url = url
|
||||
self.headers = headers or {}
|
||||
|
||||
def _create_context(self):
|
||||
return streamablehttp_client(url=self.url, headers=self.headers)
|
||||
|
||||
|
||||
def create_connection(
|
||||
transport: str,
|
||||
command: str = None,
|
||||
args: list[str] = None,
|
||||
env: dict[str, str] = None,
|
||||
url: str = None,
|
||||
headers: dict[str, str] = None,
|
||||
) -> MCPConnection:
|
||||
"""Factory function to create the appropriate MCP connection.
|
||||
|
||||
Args:
|
||||
transport: Connection type ("stdio", "sse", or "http")
|
||||
command: Command to run (stdio only)
|
||||
args: Command arguments (stdio only)
|
||||
env: Environment variables (stdio only)
|
||||
url: Server URL (sse and http only)
|
||||
headers: HTTP headers (sse and http only)
|
||||
|
||||
Returns:
|
||||
MCPConnection instance
|
||||
"""
|
||||
transport = transport.lower()
|
||||
|
||||
if transport == "stdio":
|
||||
if not command:
|
||||
raise ValueError("Command is required for stdio transport")
|
||||
return MCPConnectionStdio(command=command, args=args, env=env)
|
||||
|
||||
elif transport == "sse":
|
||||
if not url:
|
||||
raise ValueError("URL is required for sse transport")
|
||||
return MCPConnectionSSE(url=url, headers=headers)
|
||||
|
||||
elif transport in ["http", "streamable_http", "streamable-http"]:
|
||||
if not url:
|
||||
raise ValueError("URL is required for http transport")
|
||||
return MCPConnectionHTTP(url=url, headers=headers)
|
||||
|
||||
else:
|
||||
raise ValueError(f"Unsupported transport type: {transport}. Use 'stdio', 'sse', or 'http'")
|
||||
@@ -0,0 +1,373 @@
|
||||
"""MCP Server Evaluation Harness
|
||||
|
||||
This script evaluates MCP servers by running test questions against them using Claude.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
import traceback
|
||||
import xml.etree.ElementTree as ET
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from anthropic import Anthropic
|
||||
|
||||
from connections import create_connection
|
||||
|
||||
EVALUATION_PROMPT = """You are an AI assistant with access to tools.
|
||||
|
||||
When given a task, you MUST:
|
||||
1. Use the available tools to complete the task
|
||||
2. Provide summary of each step in your approach, wrapped in <summary> tags
|
||||
3. Provide feedback on the tools provided, wrapped in <feedback> tags
|
||||
4. Provide your final response, wrapped in <response> tags
|
||||
|
||||
Summary Requirements:
|
||||
- In your <summary> tags, you must explain:
|
||||
- The steps you took to complete the task
|
||||
- Which tools you used, in what order, and why
|
||||
- The inputs you provided to each tool
|
||||
- The outputs you received from each tool
|
||||
- A summary for how you arrived at the response
|
||||
|
||||
Feedback Requirements:
|
||||
- In your <feedback> tags, provide constructive feedback on the tools:
|
||||
- Comment on tool names: Are they clear and descriptive?
|
||||
- Comment on input parameters: Are they well-documented? Are required vs optional parameters clear?
|
||||
- Comment on descriptions: Do they accurately describe what the tool does?
|
||||
- Comment on any errors encountered during tool usage: Did the tool fail to execute? Did the tool return too many tokens?
|
||||
- Identify specific areas for improvement and explain WHY they would help
|
||||
- Be specific and actionable in your suggestions
|
||||
|
||||
Response Requirements:
|
||||
- Your response should be concise and directly address what was asked
|
||||
- Always wrap your final response in <response> tags
|
||||
- If you cannot solve the task return <response>NOT_FOUND</response>
|
||||
- For numeric responses, provide just the number
|
||||
- For IDs, provide just the ID
|
||||
- For names or text, provide the exact text requested
|
||||
- Your response should go last"""
|
||||
|
||||
|
||||
def parse_evaluation_file(file_path: Path) -> list[dict[str, Any]]:
|
||||
"""Parse XML evaluation file with qa_pair elements."""
|
||||
try:
|
||||
tree = ET.parse(file_path)
|
||||
root = tree.getroot()
|
||||
evaluations = []
|
||||
|
||||
for qa_pair in root.findall(".//qa_pair"):
|
||||
question_elem = qa_pair.find("question")
|
||||
answer_elem = qa_pair.find("answer")
|
||||
|
||||
if question_elem is not None and answer_elem is not None:
|
||||
evaluations.append({
|
||||
"question": (question_elem.text or "").strip(),
|
||||
"answer": (answer_elem.text or "").strip(),
|
||||
})
|
||||
|
||||
return evaluations
|
||||
except Exception as e:
|
||||
print(f"Error parsing evaluation file {file_path}: {e}")
|
||||
return []
|
||||
|
||||
|
||||
def extract_xml_content(text: str, tag: str) -> str | None:
|
||||
"""Extract content from XML tags."""
|
||||
pattern = rf"<{tag}>(.*?)</{tag}>"
|
||||
matches = re.findall(pattern, text, re.DOTALL)
|
||||
return matches[-1].strip() if matches else None
|
||||
|
||||
|
||||
async def agent_loop(
|
||||
client: Anthropic,
|
||||
model: str,
|
||||
question: str,
|
||||
tools: list[dict[str, Any]],
|
||||
connection: Any,
|
||||
) -> tuple[str, dict[str, Any]]:
|
||||
"""Run the agent loop with MCP tools."""
|
||||
messages = [{"role": "user", "content": question}]
|
||||
|
||||
response = await asyncio.to_thread(
|
||||
client.messages.create,
|
||||
model=model,
|
||||
max_tokens=4096,
|
||||
system=EVALUATION_PROMPT,
|
||||
messages=messages,
|
||||
tools=tools,
|
||||
)
|
||||
|
||||
messages.append({"role": "assistant", "content": response.content})
|
||||
|
||||
tool_metrics = {}
|
||||
|
||||
while response.stop_reason == "tool_use":
|
||||
tool_use = next(block for block in response.content if block.type == "tool_use")
|
||||
tool_name = tool_use.name
|
||||
tool_input = tool_use.input
|
||||
|
||||
tool_start_ts = time.time()
|
||||
try:
|
||||
tool_result = await connection.call_tool(tool_name, tool_input)
|
||||
tool_response = json.dumps(tool_result) if isinstance(tool_result, (dict, list)) else str(tool_result)
|
||||
except Exception as e:
|
||||
tool_response = f"Error executing tool {tool_name}: {str(e)}\n"
|
||||
tool_response += traceback.format_exc()
|
||||
tool_duration = time.time() - tool_start_ts
|
||||
|
||||
if tool_name not in tool_metrics:
|
||||
tool_metrics[tool_name] = {"count": 0, "durations": []}
|
||||
tool_metrics[tool_name]["count"] += 1
|
||||
tool_metrics[tool_name]["durations"].append(tool_duration)
|
||||
|
||||
messages.append({
|
||||
"role": "user",
|
||||
"content": [{
|
||||
"type": "tool_result",
|
||||
"tool_use_id": tool_use.id,
|
||||
"content": tool_response,
|
||||
}]
|
||||
})
|
||||
|
||||
response = await asyncio.to_thread(
|
||||
client.messages.create,
|
||||
model=model,
|
||||
max_tokens=4096,
|
||||
system=EVALUATION_PROMPT,
|
||||
messages=messages,
|
||||
tools=tools,
|
||||
)
|
||||
messages.append({"role": "assistant", "content": response.content})
|
||||
|
||||
response_text = next(
|
||||
(block.text for block in response.content if hasattr(block, "text")),
|
||||
None,
|
||||
)
|
||||
return response_text, tool_metrics
|
||||
|
||||
|
||||
async def evaluate_single_task(
|
||||
client: Anthropic,
|
||||
model: str,
|
||||
qa_pair: dict[str, Any],
|
||||
tools: list[dict[str, Any]],
|
||||
connection: Any,
|
||||
task_index: int,
|
||||
) -> dict[str, Any]:
|
||||
"""Evaluate a single QA pair with the given tools."""
|
||||
start_time = time.time()
|
||||
|
||||
print(f"Task {task_index + 1}: Running task with question: {qa_pair['question']}")
|
||||
response, tool_metrics = await agent_loop(client, model, qa_pair["question"], tools, connection)
|
||||
|
||||
response_value = extract_xml_content(response, "response")
|
||||
summary = extract_xml_content(response, "summary")
|
||||
feedback = extract_xml_content(response, "feedback")
|
||||
|
||||
duration_seconds = time.time() - start_time
|
||||
|
||||
return {
|
||||
"question": qa_pair["question"],
|
||||
"expected": qa_pair["answer"],
|
||||
"actual": response_value,
|
||||
"score": int(response_value == qa_pair["answer"]) if response_value else 0,
|
||||
"total_duration": duration_seconds,
|
||||
"tool_calls": tool_metrics,
|
||||
"num_tool_calls": sum(len(metrics["durations"]) for metrics in tool_metrics.values()),
|
||||
"summary": summary,
|
||||
"feedback": feedback,
|
||||
}
|
||||
|
||||
|
||||
REPORT_HEADER = """
|
||||
# Evaluation Report
|
||||
|
||||
## Summary
|
||||
|
||||
- **Accuracy**: {correct}/{total} ({accuracy:.1f}%)
|
||||
- **Average Task Duration**: {average_duration_s:.2f}s
|
||||
- **Average Tool Calls per Task**: {average_tool_calls:.2f}
|
||||
- **Total Tool Calls**: {total_tool_calls}
|
||||
|
||||
---
|
||||
"""
|
||||
|
||||
TASK_TEMPLATE = """
|
||||
### Task {task_num}
|
||||
|
||||
**Question**: {question}
|
||||
**Ground Truth Answer**: `{expected_answer}`
|
||||
**Actual Answer**: `{actual_answer}`
|
||||
**Correct**: {correct_indicator}
|
||||
**Duration**: {total_duration:.2f}s
|
||||
**Tool Calls**: {tool_calls}
|
||||
|
||||
**Summary**
|
||||
{summary}
|
||||
|
||||
**Feedback**
|
||||
{feedback}
|
||||
|
||||
---
|
||||
"""
|
||||
|
||||
|
||||
async def run_evaluation(
|
||||
eval_path: Path,
|
||||
connection: Any,
|
||||
model: str = "claude-3-7-sonnet-20250219",
|
||||
) -> str:
|
||||
"""Run evaluation with MCP server tools."""
|
||||
print("🚀 Starting Evaluation")
|
||||
|
||||
client = Anthropic()
|
||||
|
||||
tools = await connection.list_tools()
|
||||
print(f"📋 Loaded {len(tools)} tools from MCP server")
|
||||
|
||||
qa_pairs = parse_evaluation_file(eval_path)
|
||||
print(f"📋 Loaded {len(qa_pairs)} evaluation tasks")
|
||||
|
||||
results = []
|
||||
for i, qa_pair in enumerate(qa_pairs):
|
||||
print(f"Processing task {i + 1}/{len(qa_pairs)}")
|
||||
result = await evaluate_single_task(client, model, qa_pair, tools, connection, i)
|
||||
results.append(result)
|
||||
|
||||
correct = sum(r["score"] for r in results)
|
||||
accuracy = (correct / len(results)) * 100 if results else 0
|
||||
average_duration_s = sum(r["total_duration"] for r in results) / len(results) if results else 0
|
||||
average_tool_calls = sum(r["num_tool_calls"] for r in results) / len(results) if results else 0
|
||||
total_tool_calls = sum(r["num_tool_calls"] for r in results)
|
||||
|
||||
report = REPORT_HEADER.format(
|
||||
correct=correct,
|
||||
total=len(results),
|
||||
accuracy=accuracy,
|
||||
average_duration_s=average_duration_s,
|
||||
average_tool_calls=average_tool_calls,
|
||||
total_tool_calls=total_tool_calls,
|
||||
)
|
||||
|
||||
report += "".join([
|
||||
TASK_TEMPLATE.format(
|
||||
task_num=i + 1,
|
||||
question=qa_pair["question"],
|
||||
expected_answer=qa_pair["answer"],
|
||||
actual_answer=result["actual"] or "N/A",
|
||||
correct_indicator="✅" if result["score"] else "❌",
|
||||
total_duration=result["total_duration"],
|
||||
tool_calls=json.dumps(result["tool_calls"], indent=2),
|
||||
summary=result["summary"] or "N/A",
|
||||
feedback=result["feedback"] or "N/A",
|
||||
)
|
||||
for i, (qa_pair, result) in enumerate(zip(qa_pairs, results))
|
||||
])
|
||||
|
||||
return report
|
||||
|
||||
|
||||
def parse_headers(header_list: list[str]) -> dict[str, str]:
|
||||
"""Parse header strings in format 'Key: Value' into a dictionary."""
|
||||
headers = {}
|
||||
if not header_list:
|
||||
return headers
|
||||
|
||||
for header in header_list:
|
||||
if ":" in header:
|
||||
key, value = header.split(":", 1)
|
||||
headers[key.strip()] = value.strip()
|
||||
else:
|
||||
print(f"Warning: Ignoring malformed header: {header}")
|
||||
return headers
|
||||
|
||||
|
||||
def parse_env_vars(env_list: list[str]) -> dict[str, str]:
|
||||
"""Parse environment variable strings in format 'KEY=VALUE' into a dictionary."""
|
||||
env = {}
|
||||
if not env_list:
|
||||
return env
|
||||
|
||||
for env_var in env_list:
|
||||
if "=" in env_var:
|
||||
key, value = env_var.split("=", 1)
|
||||
env[key.strip()] = value.strip()
|
||||
else:
|
||||
print(f"Warning: Ignoring malformed environment variable: {env_var}")
|
||||
return env
|
||||
|
||||
|
||||
async def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Evaluate MCP servers using test questions",
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||
epilog="""
|
||||
Examples:
|
||||
# Evaluate a local stdio MCP server
|
||||
python evaluation.py -t stdio -c python -a my_server.py eval.xml
|
||||
|
||||
# Evaluate an SSE MCP server
|
||||
python evaluation.py -t sse -u https://example.com/mcp -H "Authorization: Bearer token" eval.xml
|
||||
|
||||
# Evaluate an HTTP MCP server with custom model
|
||||
python evaluation.py -t http -u https://example.com/mcp -m claude-3-5-sonnet-20241022 eval.xml
|
||||
""",
|
||||
)
|
||||
|
||||
parser.add_argument("eval_file", type=Path, help="Path to evaluation XML file")
|
||||
parser.add_argument("-t", "--transport", choices=["stdio", "sse", "http"], default="stdio", help="Transport type (default: stdio)")
|
||||
parser.add_argument("-m", "--model", default="claude-3-7-sonnet-20250219", help="Claude model to use (default: claude-3-7-sonnet-20250219)")
|
||||
|
||||
stdio_group = parser.add_argument_group("stdio options")
|
||||
stdio_group.add_argument("-c", "--command", help="Command to run MCP server (stdio only)")
|
||||
stdio_group.add_argument("-a", "--args", nargs="+", help="Arguments for the command (stdio only)")
|
||||
stdio_group.add_argument("-e", "--env", nargs="+", help="Environment variables in KEY=VALUE format (stdio only)")
|
||||
|
||||
remote_group = parser.add_argument_group("sse/http options")
|
||||
remote_group.add_argument("-u", "--url", help="MCP server URL (sse/http only)")
|
||||
remote_group.add_argument("-H", "--header", nargs="+", dest="headers", help="HTTP headers in 'Key: Value' format (sse/http only)")
|
||||
|
||||
parser.add_argument("-o", "--output", type=Path, help="Output file for evaluation report (default: stdout)")
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
if not args.eval_file.exists():
|
||||
print(f"Error: Evaluation file not found: {args.eval_file}")
|
||||
sys.exit(1)
|
||||
|
||||
headers = parse_headers(args.headers) if args.headers else None
|
||||
env_vars = parse_env_vars(args.env) if args.env else None
|
||||
|
||||
try:
|
||||
connection = create_connection(
|
||||
transport=args.transport,
|
||||
command=args.command,
|
||||
args=args.args,
|
||||
env=env_vars,
|
||||
url=args.url,
|
||||
headers=headers,
|
||||
)
|
||||
except ValueError as e:
|
||||
print(f"Error: {e}")
|
||||
sys.exit(1)
|
||||
|
||||
print(f"🔗 Connecting to MCP server via {args.transport}...")
|
||||
|
||||
async with connection:
|
||||
print("✅ Connected successfully")
|
||||
report = await run_evaluation(args.eval_file, connection, args.model)
|
||||
|
||||
if args.output:
|
||||
args.output.write_text(report)
|
||||
print(f"\n✅ Report saved to {args.output}")
|
||||
else:
|
||||
print("\n" + report)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,22 @@
|
||||
<evaluation>
|
||||
<qa_pair>
|
||||
<question>Calculate the compound interest on $10,000 invested at 5% annual interest rate, compounded monthly for 3 years. What is the final amount in dollars (rounded to 2 decimal places)?</question>
|
||||
<answer>11614.72</answer>
|
||||
</qa_pair>
|
||||
<qa_pair>
|
||||
<question>A projectile is launched at a 45-degree angle with an initial velocity of 50 m/s. Calculate the total distance (in meters) it has traveled from the launch point after 2 seconds, assuming g=9.8 m/s². Round to 2 decimal places.</question>
|
||||
<answer>87.25</answer>
|
||||
</qa_pair>
|
||||
<qa_pair>
|
||||
<question>A sphere has a volume of 500 cubic meters. Calculate its surface area in square meters. Round to 2 decimal places.</question>
|
||||
<answer>304.65</answer>
|
||||
</qa_pair>
|
||||
<qa_pair>
|
||||
<question>Calculate the population standard deviation of this dataset: [12, 15, 18, 22, 25, 30, 35]. Round to 2 decimal places.</question>
|
||||
<answer>7.61</answer>
|
||||
</qa_pair>
|
||||
<qa_pair>
|
||||
<question>Calculate the pH of a solution with a hydrogen ion concentration of 3.5 × 10^-5 M. Round to 2 decimal places.</question>
|
||||
<answer>4.46</answer>
|
||||
</qa_pair>
|
||||
</evaluation>
|
||||
@@ -0,0 +1,2 @@
|
||||
anthropic>=0.39.0
|
||||
mcp>=1.1.0
|
||||
@@ -0,0 +1,159 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect } from 'react'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Card, CardContent } from '@/components/ui/card'
|
||||
import { KPIHeroCards } from '@/components/kpi/KPIHeroCards'
|
||||
import { KPIOperationalGrid } from '@/components/kpi/KPIOperationalGrid'
|
||||
import { KPITrendChart } from '@/components/kpi/KPITrendChart'
|
||||
import type { FiscalPeriod, KPIReport } from '@/types'
|
||||
|
||||
export default function NyckeltalPage() {
|
||||
const [periods, setPeriods] = useState<FiscalPeriod[]>([])
|
||||
const [selectedPeriod, setSelectedPeriod] = useState('')
|
||||
const [report, setReport] = useState<KPIReport | null>(null)
|
||||
const [isLoadingInit, setIsLoadingInit] = useState(true)
|
||||
const [isLoadingReport, setIsLoadingReport] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
async function fetchPeriods() {
|
||||
try {
|
||||
const res = await fetch('/api/bookkeeping/fiscal-periods')
|
||||
const { data } = await res.json()
|
||||
setPeriods(data || [])
|
||||
if (data && data.length > 0) {
|
||||
setSelectedPeriod(data[0].id)
|
||||
}
|
||||
} catch {
|
||||
setError('Kunde inte hämta räkenskapsår')
|
||||
} finally {
|
||||
setIsLoadingInit(false)
|
||||
}
|
||||
}
|
||||
fetchPeriods()
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedPeriod) return
|
||||
let cancelled = false
|
||||
|
||||
async function fetchReport() {
|
||||
setIsLoadingReport(true)
|
||||
setError(null)
|
||||
try {
|
||||
const res = await fetch(`/api/reports/kpi?period_id=${selectedPeriod}`)
|
||||
if (!res.ok) throw new Error('Kunde inte hämta nyckeltal')
|
||||
const { data } = await res.json()
|
||||
if (!cancelled) setReport(data)
|
||||
} catch {
|
||||
if (!cancelled) setError('Kunde inte hämta nyckeltal')
|
||||
} finally {
|
||||
if (!cancelled) setIsLoadingReport(false)
|
||||
}
|
||||
}
|
||||
fetchReport()
|
||||
return () => { cancelled = true }
|
||||
}, [selectedPeriod])
|
||||
|
||||
if (isLoadingInit) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h1 className="font-display text-2xl md:text-3xl font-medium tracking-tight">Nyckeltal</h1>
|
||||
<p className="text-muted-foreground">Översikt av företagets ekonomiska hälsa</p>
|
||||
</div>
|
||||
<LoadingSkeleton />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
|
||||
<div>
|
||||
<h1 className="font-display text-2xl md:text-3xl font-medium tracking-tight">Nyckeltal</h1>
|
||||
<p className="text-muted-foreground">Översikt av företagets ekonomiska hälsa</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Period selector */}
|
||||
{periods.length > 0 && (
|
||||
<div>
|
||||
<Label>Räkenskapsår</Label>
|
||||
<select
|
||||
value={selectedPeriod}
|
||||
onChange={(e) => setSelectedPeriod(e.target.value)}
|
||||
className="w-full mt-1 max-w-xs rounded-md border border-input bg-background px-3 py-2 text-sm"
|
||||
>
|
||||
{periods.map((p) => (
|
||||
<option key={p.id} value={p.id}>
|
||||
{p.name} ({p.period_start} — {p.period_end})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<Card>
|
||||
<CardContent className="py-8 text-center text-muted-foreground">
|
||||
<p>{error}</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{isLoadingReport && <LoadingSkeleton />}
|
||||
|
||||
{!isLoadingReport && !error && report && (
|
||||
<>
|
||||
<KPIHeroCards report={report} />
|
||||
<KPIOperationalGrid report={report} />
|
||||
{report.months.length > 0 && <KPITrendChart months={report.months} />}
|
||||
</>
|
||||
)}
|
||||
|
||||
{!isLoadingReport && !error && !report && periods.length === 0 && (
|
||||
<Card>
|
||||
<CardContent className="py-12 text-center text-muted-foreground">
|
||||
<p>Inget räkenskapsår hittades. Skapa ett räkenskapsår för att se nyckeltal.</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function LoadingSkeleton() {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
|
||||
{[1, 2, 3, 4].map((i) => (
|
||||
<Card key={i}>
|
||||
<CardContent className="p-5 space-y-2">
|
||||
<div className="h-3 bg-muted rounded w-20 animate-pulse" />
|
||||
<div className="h-7 bg-muted rounded w-28 animate-pulse" />
|
||||
<div className="h-3 bg-muted rounded w-16 animate-pulse" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
{[1, 2, 3, 4].map((i) => (
|
||||
<Card key={i}>
|
||||
<CardContent className="p-5 space-y-2">
|
||||
<div className="h-3 bg-muted rounded w-24 animate-pulse" />
|
||||
<div className="h-6 bg-muted rounded w-20 animate-pulse" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
<Card>
|
||||
<CardContent className="p-5 space-y-3">
|
||||
<div className="h-4 bg-muted rounded w-40 animate-pulse" />
|
||||
<div className="h-56 bg-muted rounded animate-pulse" />
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -37,6 +37,7 @@ import { validateBankgiroNumber, formatBankgiroNumber } from '@/lib/bankgiro/luh
|
||||
import { CalendarFeedSettings } from '@/components/settings/CalendarFeedSettings'
|
||||
import { getSettingsPanel } from '@/lib/extensions/settings-panel-registry'
|
||||
import { SecuritySettings } from '@/components/settings/SecuritySettings'
|
||||
import { ApiKeysPanel } from '@/components/settings/ApiKeysPanel'
|
||||
import { ENABLED_EXTENSION_IDS } from '@/lib/extensions/_generated/enabled-extensions'
|
||||
|
||||
const BankingPanel = getSettingsPanel('enable-banking')
|
||||
@@ -52,6 +53,7 @@ export default function SettingsPage() {
|
||||
const [settings, setSettings] = useState<CompanySettings | null>(null)
|
||||
const hasBankingExtension = ENABLED_EXTENSION_IDS.has('enable-banking')
|
||||
const hasCalendarExtension = ENABLED_EXTENSION_IDS.has('calendar')
|
||||
const hasMcpExtension = ENABLED_EXTENSION_IDS.has('mcp-server')
|
||||
const [bankConnectionError, setBankConnectionError] = useState<string | null>(null)
|
||||
const [bankgiroError, setBankgiroError] = useState<string | null>(null)
|
||||
const [showDeleteDialog, setShowDeleteDialog] = useState(false)
|
||||
@@ -69,6 +71,7 @@ export default function SettingsPage() {
|
||||
{ value: 'calendar', label: 'Kalender', show: hasCalendarExtension },
|
||||
{ value: 'security', label: 'Säkerhet', show: true },
|
||||
{ value: 'appearance', label: 'Utseende', show: true },
|
||||
{ value: 'api', label: 'API', show: hasMcpExtension },
|
||||
{ value: 'account', label: 'Konto', show: true },
|
||||
].filter(t => t.show)
|
||||
|
||||
@@ -702,6 +705,13 @@ export default function SettingsPage() {
|
||||
</Card>
|
||||
</TabsContent>
|
||||
|
||||
{/* API keys */}
|
||||
{hasMcpExtension && (
|
||||
<TabsContent value="api">
|
||||
<ApiKeysPanel />
|
||||
</TabsContent>
|
||||
)}
|
||||
|
||||
{/* Account settings */}
|
||||
<TabsContent value="account" className="space-y-6">
|
||||
<Card>
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
|
||||
/**
|
||||
* RFC 8414 — OAuth 2.0 Authorization Server Metadata.
|
||||
* Tells MCP clients where the authorize/token endpoints are.
|
||||
*/
|
||||
export async function GET() {
|
||||
const appUrl = process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000'
|
||||
|
||||
return NextResponse.json({
|
||||
issuer: appUrl,
|
||||
authorization_endpoint: `${appUrl}/api/mcp-oauth/authorize`,
|
||||
token_endpoint: `${appUrl}/api/mcp-oauth/token`,
|
||||
registration_endpoint: `${appUrl}/api/mcp-oauth/register`,
|
||||
response_types_supported: ['code'],
|
||||
grant_types_supported: ['authorization_code'],
|
||||
code_challenge_methods_supported: ['S256'],
|
||||
token_endpoint_auth_methods_supported: ['none', 'client_secret_post'],
|
||||
scopes_supported: ['mcp'],
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
|
||||
/**
|
||||
* RFC 9728 — Protected Resource Metadata.
|
||||
* Tells MCP clients which authorization server to use.
|
||||
*/
|
||||
export async function GET() {
|
||||
const appUrl = process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000'
|
||||
|
||||
return NextResponse.json({
|
||||
resource: `${appUrl}/api/extensions/ext/mcp-server/mcp`,
|
||||
authorization_servers: [appUrl],
|
||||
scopes_supported: ['mcp'],
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createAuthCode } from '@/lib/auth/oauth-codes'
|
||||
|
||||
/**
|
||||
* OAuth 2.0 Authorization Endpoint.
|
||||
*
|
||||
* GET → show consent page (or redirect to login)
|
||||
* POST → process consent, create auth code, redirect to callback
|
||||
*
|
||||
* The API key is NOT created here — it's created in the token endpoint
|
||||
* after PKCE verification, preventing orphaned keys on abandoned flows.
|
||||
*/
|
||||
|
||||
// Known Claude callback URLs — reject all others to prevent open redirect
|
||||
const ALLOWED_REDIRECT_PATTERNS = [
|
||||
/^https:\/\/claude\.ai\/api\/mcp\/auth_callback$/,
|
||||
/^https:\/\/claude\.com\/api\/mcp\/auth_callback$/,
|
||||
/^http:\/\/localhost(:\d+)?\//, // Local development
|
||||
/^http:\/\/127\.0\.0\.1(:\d+)?\//, // Local development
|
||||
]
|
||||
|
||||
function isAllowedRedirectUri(uri: string): boolean {
|
||||
return ALLOWED_REDIRECT_PATTERNS.some((pattern) => pattern.test(uri))
|
||||
}
|
||||
|
||||
function buildLoginRedirect(request: Request): Response {
|
||||
const url = new URL(request.url)
|
||||
const next = `${url.pathname}${url.search}`
|
||||
return NextResponse.redirect(
|
||||
new URL(`/login?next=${encodeURIComponent(next)}`, url.origin)
|
||||
)
|
||||
}
|
||||
|
||||
function errorRedirect(redirectUri: string, state: string | null, error: string, desc: string): Response {
|
||||
const url = new URL(redirectUri)
|
||||
url.searchParams.set('error', error)
|
||||
url.searchParams.set('error_description', desc)
|
||||
if (state) url.searchParams.set('state', state)
|
||||
return NextResponse.redirect(url.toString())
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /api/mcp-oauth/authorize — show consent page
|
||||
*/
|
||||
export async function GET(request: Request) {
|
||||
const url = new URL(request.url)
|
||||
const redirectUri = url.searchParams.get('redirect_uri')
|
||||
const state = url.searchParams.get('state')
|
||||
const codeChallenge = url.searchParams.get('code_challenge')
|
||||
const codeChallengeMethod = url.searchParams.get('code_challenge_method') || 'S256'
|
||||
const responseType = url.searchParams.get('response_type')
|
||||
|
||||
if (responseType !== 'code') {
|
||||
return NextResponse.json(
|
||||
{ error: 'unsupported_response_type' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
if (!redirectUri) {
|
||||
return NextResponse.json(
|
||||
{ error: 'invalid_request', error_description: 'redirect_uri is required' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
// Validate redirect_uri against allowlist (prevents open redirect)
|
||||
if (!isAllowedRedirectUri(redirectUri)) {
|
||||
return NextResponse.json(
|
||||
{ error: 'invalid_request', error_description: 'redirect_uri is not allowed' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
if (codeChallengeMethod !== 'S256') {
|
||||
return NextResponse.json(
|
||||
{ error: 'invalid_request', error_description: 'Only S256 code_challenge_method is supported' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
// Check if user is logged in
|
||||
const supabase = await createClient()
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
|
||||
if (!user) {
|
||||
return buildLoginRedirect(request)
|
||||
}
|
||||
|
||||
// Get company name for the consent page
|
||||
const { data: settings } = await supabase
|
||||
.from('company_settings')
|
||||
.select('company_name')
|
||||
.eq('user_id', user.id)
|
||||
.single()
|
||||
|
||||
const companyName = settings?.company_name || user.email
|
||||
|
||||
// Render consent page
|
||||
const html = `<!DOCTYPE html>
|
||||
<html lang="sv">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="translate" content="no">
|
||||
<title>Anslut MCP-klient — gnubok</title>
|
||||
<style>
|
||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||
body { font-family: system-ui, -apple-system, sans-serif; background: #fafafa; color: #111; display: flex; align-items: center; justify-content: center; min-height: 100vh; padding: 1rem; }
|
||||
.card { background: white; border-radius: 12px; border: 1px solid #e5e5e5; padding: 2rem; max-width: 400px; width: 100%; }
|
||||
h1 { font-size: 1.25rem; font-weight: 600; margin-bottom: 0.5rem; }
|
||||
p { font-size: 0.875rem; color: #666; line-height: 1.5; margin-bottom: 1rem; }
|
||||
.account { font-size: 0.875rem; color: #111; font-weight: 500; background: #f5f5f5; padding: 0.75rem 1rem; border-radius: 8px; margin-bottom: 1.5rem; }
|
||||
.permissions { font-size: 0.8125rem; color: #444; margin-bottom: 1.5rem; }
|
||||
.permissions li { margin-bottom: 0.25rem; }
|
||||
.actions { display: flex; gap: 0.75rem; }
|
||||
button { flex: 1; padding: 0.625rem 1rem; border-radius: 8px; font-size: 0.875rem; font-weight: 500; cursor: pointer; border: 1px solid #e5e5e5; }
|
||||
.allow { background: #111; color: white; border-color: #111; }
|
||||
.allow:hover { background: #333; }
|
||||
.deny { background: white; color: #111; }
|
||||
.deny:hover { background: #f5f5f5; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="card">
|
||||
<h1>Anslut MCP-klient</h1>
|
||||
<p>En extern applikation vill ansluta till ditt gnubok-konto.</p>
|
||||
<div class="account">${escapeHtml(companyName)}</div>
|
||||
<ul class="permissions">
|
||||
<li>Visa och kategorisera transaktioner</li>
|
||||
<li>Skapa och visa fakturor</li>
|
||||
<li>Visa kunder och rapporter</li>
|
||||
<li>Skapa verifikationer</li>
|
||||
</ul>
|
||||
<div class="actions">
|
||||
<form method="POST" action="${url.pathname}${url.search}" style="flex:1;display:flex;">
|
||||
<input type="hidden" name="consent" value="deny">
|
||||
<button type="submit" class="deny" style="width:100%;">Neka</button>
|
||||
</form>
|
||||
<form method="POST" action="${url.pathname}${url.search}" style="flex:1;display:flex;">
|
||||
<input type="hidden" name="consent" value="allow">
|
||||
<button type="submit" class="allow" style="width:100%;">Tillåt</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>`
|
||||
|
||||
return new Response(html, {
|
||||
headers: { 'Content-Type': 'text/html; charset=utf-8' },
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/mcp-oauth/authorize — process consent, issue auth code
|
||||
*/
|
||||
export async function POST(request: Request) {
|
||||
const url = new URL(request.url)
|
||||
const redirectUri = url.searchParams.get('redirect_uri')
|
||||
const state = url.searchParams.get('state')
|
||||
const codeChallenge = url.searchParams.get('code_challenge') || ''
|
||||
const codeChallengeMethod = url.searchParams.get('code_challenge_method') || 'S256'
|
||||
|
||||
if (!redirectUri) {
|
||||
return NextResponse.json({ error: 'invalid_request' }, { status: 400 })
|
||||
}
|
||||
|
||||
if (!isAllowedRedirectUri(redirectUri)) {
|
||||
return NextResponse.json(
|
||||
{ error: 'invalid_request', error_description: 'redirect_uri is not allowed' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
// Check auth
|
||||
const supabase = await createClient()
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
|
||||
if (!user) {
|
||||
return buildLoginRedirect(request)
|
||||
}
|
||||
|
||||
// Parse form body
|
||||
const formData = await request.formData()
|
||||
const consent = formData.get('consent')
|
||||
|
||||
if (consent !== 'allow') {
|
||||
return errorRedirect(redirectUri, state, 'access_denied', 'User denied the request')
|
||||
}
|
||||
|
||||
// Create auth code with userId (NO API key — that's created at /token after PKCE)
|
||||
const code = createAuthCode({
|
||||
userId: user.id,
|
||||
codeChallenge,
|
||||
codeChallengeMethod,
|
||||
redirectUri,
|
||||
})
|
||||
|
||||
// Redirect to callback with the code
|
||||
const callbackUrl = new URL(redirectUri)
|
||||
callbackUrl.searchParams.set('code', code)
|
||||
if (state) callbackUrl.searchParams.set('state', state)
|
||||
|
||||
return NextResponse.redirect(callbackUrl.toString())
|
||||
}
|
||||
|
||||
function escapeHtml(str: string): string {
|
||||
return str
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import crypto from 'crypto'
|
||||
|
||||
/**
|
||||
* RFC 7591 — Dynamic Client Registration.
|
||||
* Claude Desktop registers itself as an OAuth client before starting the auth flow.
|
||||
* We accept any registration and return a client_id.
|
||||
*/
|
||||
export async function POST(request: Request) {
|
||||
let body: Record<string, unknown>
|
||||
try {
|
||||
body = await request.json()
|
||||
} catch {
|
||||
return NextResponse.json({ error: 'invalid_request' }, { status: 400 })
|
||||
}
|
||||
|
||||
const clientId = crypto.randomUUID()
|
||||
|
||||
return NextResponse.json({
|
||||
client_id: clientId,
|
||||
client_name: (body.client_name as string) || 'MCP Client',
|
||||
redirect_uris: body.redirect_uris || [],
|
||||
grant_types: ['authorization_code'],
|
||||
response_types: ['code'],
|
||||
token_endpoint_auth_method: 'none',
|
||||
}, { status: 201 })
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { decryptAuthCode, verifyPkce, hashAuthCode } from '@/lib/auth/oauth-codes'
|
||||
import { generateApiKey } from '@/lib/auth/api-keys'
|
||||
import { createServiceClientNoCookies } from '@/lib/auth/api-keys'
|
||||
|
||||
/**
|
||||
* OAuth 2.0 Token Endpoint.
|
||||
*
|
||||
* Exchanges an authorization code for an API key (access token).
|
||||
* 1. Decrypts the stateless auth code
|
||||
* 2. Checks for replay (single-use enforcement per OAuth 2.1 §4.1.2)
|
||||
* 3. Verifies PKCE (S256 only)
|
||||
* 4. Creates the API key (deferred from /authorize to prevent orphaned keys)
|
||||
* 5. Returns the key as a bearer token
|
||||
*/
|
||||
export async function POST(request: Request) {
|
||||
let params: URLSearchParams
|
||||
|
||||
const contentType = request.headers.get('content-type') || ''
|
||||
if (contentType.includes('application/x-www-form-urlencoded')) {
|
||||
const text = await request.text()
|
||||
params = new URLSearchParams(text)
|
||||
} else if (contentType.includes('application/json')) {
|
||||
const json = await request.json()
|
||||
params = new URLSearchParams(json as Record<string, string>)
|
||||
} else {
|
||||
return NextResponse.json({ error: 'unsupported_content_type' }, { status: 400 })
|
||||
}
|
||||
|
||||
const grantType = params.get('grant_type')
|
||||
const code = params.get('code')
|
||||
const codeVerifier = params.get('code_verifier')
|
||||
const redirectUri = params.get('redirect_uri')
|
||||
|
||||
if (grantType !== 'authorization_code') {
|
||||
return NextResponse.json(
|
||||
{ error: 'unsupported_grant_type', error_description: 'Only authorization_code is supported' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
if (!code) {
|
||||
return NextResponse.json(
|
||||
{ error: 'invalid_request', error_description: 'Missing code parameter' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
// Decrypt the auth code
|
||||
const payload = decryptAuthCode(code)
|
||||
if (!payload) {
|
||||
return NextResponse.json(
|
||||
{ error: 'invalid_grant', error_description: 'Invalid or expired authorization code' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
// Verify redirect_uri matches
|
||||
if (redirectUri && redirectUri !== payload.redirectUri) {
|
||||
return NextResponse.json(
|
||||
{ error: 'invalid_grant', error_description: 'redirect_uri mismatch' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
// Verify PKCE (S256 only)
|
||||
if (!codeVerifier) {
|
||||
return NextResponse.json(
|
||||
{ error: 'invalid_request', error_description: 'code_verifier is required' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
if (!verifyPkce(codeVerifier, payload.codeChallenge)) {
|
||||
return NextResponse.json(
|
||||
{ error: 'invalid_grant', error_description: 'PKCE verification failed' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
// Single-use enforcement: check and mark code as used (atomically via unique constraint)
|
||||
const codeHash = hashAuthCode(code)
|
||||
const supabase = createServiceClientNoCookies()
|
||||
|
||||
const { error: replayError } = await supabase
|
||||
.from('oauth_used_codes')
|
||||
.insert({ code_hash: codeHash })
|
||||
|
||||
if (replayError) {
|
||||
// Unique constraint violation = code already used
|
||||
return NextResponse.json(
|
||||
{ error: 'invalid_grant', error_description: 'Authorization code already used' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
// Clean up expired codes (non-blocking, best-effort)
|
||||
supabase
|
||||
.from('oauth_used_codes')
|
||||
.delete()
|
||||
.lt('created_at', new Date(Date.now() - 10 * 60 * 1000).toISOString())
|
||||
.then(() => {})
|
||||
|
||||
// Create the API key now (after PKCE verification — prevents orphaned keys)
|
||||
const { key, hash, prefix } = generateApiKey()
|
||||
|
||||
const { error: insertError } = await supabase
|
||||
.from('api_keys')
|
||||
.insert({
|
||||
user_id: payload.userId,
|
||||
key_hash: hash,
|
||||
key_prefix: prefix,
|
||||
name: 'MCP-klient (OAuth)',
|
||||
})
|
||||
|
||||
if (insertError) {
|
||||
return NextResponse.json(
|
||||
{ error: 'server_error', error_description: 'Failed to create API key' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
access_token: key,
|
||||
token_type: 'Bearer',
|
||||
scope: 'mcp',
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { generateIncomeStatement } from '@/lib/reports/income-statement'
|
||||
import { generateTrialBalance } from '@/lib/reports/trial-balance'
|
||||
import { generateARLedger } from '@/lib/reports/ar-ledger'
|
||||
import { generateMonthlyBreakdown } from '@/lib/reports/monthly-breakdown'
|
||||
import {
|
||||
calculateGrossMargin,
|
||||
calculateCashPosition,
|
||||
calculateRevenueGrowth,
|
||||
calculateExpenseRatio,
|
||||
calculateAvgPaymentDays,
|
||||
} from '@/lib/reports/kpi'
|
||||
import type { KPIReport } from '@/types'
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const supabase = await createClient()
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
|
||||
const { searchParams } = new URL(request.url)
|
||||
const periodId = searchParams.get('period_id')
|
||||
if (!periodId) {
|
||||
return NextResponse.json({ error: 'period_id is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
// Fetch fiscal period info
|
||||
const { data: period, error: periodError } = await supabase
|
||||
.from('fiscal_periods')
|
||||
.select('*')
|
||||
.eq('id', periodId)
|
||||
.eq('user_id', user.id)
|
||||
.single()
|
||||
|
||||
if (periodError || !period) {
|
||||
return NextResponse.json({ error: 'Fiscal period not found' }, { status: 404 })
|
||||
}
|
||||
|
||||
// Run independent queries in parallel
|
||||
const [
|
||||
incomeStatement,
|
||||
trialBalanceResult,
|
||||
arLedger,
|
||||
monthlyBreakdown,
|
||||
paidInvoicesResult,
|
||||
] = await Promise.all([
|
||||
generateIncomeStatement(supabase, user.id, periodId),
|
||||
generateTrialBalance(supabase, user.id, periodId),
|
||||
generateARLedger(supabase, user.id),
|
||||
generateMonthlyBreakdown(supabase, user.id, periodId),
|
||||
supabase
|
||||
.from('invoices')
|
||||
.select('invoice_date, paid_at')
|
||||
.eq('user_id', user.id)
|
||||
.eq('status', 'paid')
|
||||
.not('paid_at', 'is', null)
|
||||
.gte('invoice_date', period.period_start)
|
||||
.lte('invoice_date', period.period_end),
|
||||
])
|
||||
|
||||
const paidInvoices = (paidInvoicesResult.data || []) as { invoice_date: string; paid_at: string }[]
|
||||
|
||||
// Calculate VAT liability from trial balance (output VAT - input VAT)
|
||||
const vatOutputAccounts = ['2611', '2621', '2631']
|
||||
const vatInputAccounts = ['2641', '2645']
|
||||
const outputVat = trialBalanceResult.rows
|
||||
.filter((r) => vatOutputAccounts.includes(r.account_number))
|
||||
.reduce((sum, r) => sum + (r.closing_credit - r.closing_debit), 0)
|
||||
const inputVat = trialBalanceResult.rows
|
||||
.filter((r) => vatInputAccounts.includes(r.account_number))
|
||||
.reduce((sum, r) => sum + (r.closing_debit - r.closing_credit), 0)
|
||||
const vatLiability = Math.round((outputVat - inputVat) * 100) / 100
|
||||
|
||||
// Revenue growth: only for closed periods, compare with previous period
|
||||
let revenueGrowth: number | null = null
|
||||
if (period.is_closed && period.previous_period_id) {
|
||||
const prevStatement = await generateIncomeStatement(
|
||||
supabase,
|
||||
user.id,
|
||||
period.previous_period_id
|
||||
)
|
||||
revenueGrowth = calculateRevenueGrowth(
|
||||
incomeStatement.total_revenue,
|
||||
prevStatement.total_revenue
|
||||
)
|
||||
}
|
||||
|
||||
const report: KPIReport = {
|
||||
grossMargin: calculateGrossMargin(incomeStatement),
|
||||
netResult: incomeStatement.net_result,
|
||||
cashPosition: calculateCashPosition(trialBalanceResult.rows),
|
||||
outstandingReceivables: arLedger.total_outstanding,
|
||||
overdueReceivables: arLedger.total_overdue,
|
||||
revenueGrowth,
|
||||
expenseRatio: calculateExpenseRatio(incomeStatement),
|
||||
avgPaymentDays: calculateAvgPaymentDays(paidInvoices),
|
||||
paidInvoiceCount: paidInvoices.length,
|
||||
vatLiability,
|
||||
totalRevenue: incomeStatement.total_revenue,
|
||||
totalExpenses: incomeStatement.total_expenses,
|
||||
periodComplete: period.is_closed,
|
||||
months: monthlyBreakdown.months,
|
||||
period: { start: period.period_start, end: period.period_end },
|
||||
}
|
||||
|
||||
return NextResponse.json({ data: report })
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
|
||||
/**
|
||||
* DELETE /api/settings/api-keys/[id] — Revoke an API key (soft delete)
|
||||
*/
|
||||
export async function DELETE(
|
||||
_request: Request,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
const supabase = await createClient()
|
||||
const { id } = await params
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const { error } = await supabase
|
||||
.from('api_keys')
|
||||
.update({ revoked_at: new Date().toISOString() })
|
||||
.eq('id', id)
|
||||
.eq('user_id', user.id)
|
||||
.is('revoked_at', null)
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 })
|
||||
}
|
||||
|
||||
return NextResponse.json({ success: true })
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { generateApiKey, hashApiKey } from '@/lib/auth/api-keys'
|
||||
|
||||
/**
|
||||
* GET /api/settings/api-keys — List user's API keys (never exposes the key itself)
|
||||
*/
|
||||
export async function GET() {
|
||||
const supabase = await createClient()
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('api_keys')
|
||||
.select('id, key_prefix, name, scopes, rate_limit_rpm, last_used_at, revoked_at, created_at')
|
||||
.eq('user_id', user.id)
|
||||
.order('created_at', { ascending: false })
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 })
|
||||
}
|
||||
|
||||
return NextResponse.json({ data })
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/settings/api-keys — Create a new API key
|
||||
* Returns the full key ONCE. After this, only the prefix is available.
|
||||
*/
|
||||
export async function POST(request: Request) {
|
||||
const supabase = await createClient()
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
let name = 'Unnamed key'
|
||||
try {
|
||||
const body = await request.json()
|
||||
if (body.name && typeof body.name === 'string') {
|
||||
name = body.name.slice(0, 100)
|
||||
}
|
||||
} catch {
|
||||
// Empty body is fine, use default name
|
||||
}
|
||||
|
||||
// Limit to 10 active keys per user
|
||||
const { count } = await supabase
|
||||
.from('api_keys')
|
||||
.select('id', { count: 'exact', head: true })
|
||||
.eq('user_id', user.id)
|
||||
.is('revoked_at', null)
|
||||
|
||||
if (count !== null && count >= 10) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Maximum 10 active API keys allowed' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
const { key, hash, prefix } = generateApiKey()
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('api_keys')
|
||||
.insert({
|
||||
user_id: user.id,
|
||||
key_hash: hash,
|
||||
key_prefix: prefix,
|
||||
name,
|
||||
})
|
||||
.select('id, key_prefix, name, created_at')
|
||||
.single()
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 })
|
||||
}
|
||||
|
||||
// Return the full key exactly once
|
||||
return NextResponse.json({
|
||||
data: {
|
||||
...data,
|
||||
key, // Only time the full key is returned
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -24,6 +24,7 @@ import {
|
||||
Building2,
|
||||
FileInput,
|
||||
Wallet,
|
||||
TrendingUp,
|
||||
} from 'lucide-react'
|
||||
import { resolveIcon } from '@/lib/extensions/icon-resolver'
|
||||
import type { EntityType } from '@/types'
|
||||
@@ -54,6 +55,7 @@ interface NavItem {
|
||||
// All nav items for sidebar and mobile drawer
|
||||
const navItems: NavItem[] = [
|
||||
{ href: '/', label: 'Översikt', icon: LayoutDashboard, group: 'main' },
|
||||
{ href: '/nyckeltal', label: 'Nyckeltal', icon: TrendingUp, group: 'main' },
|
||||
{ href: '/deadlines', label: 'Deadlines', icon: Calendar, group: 'main' },
|
||||
{ href: '/invoices', label: 'Fakturor', icon: Receipt, group: 'finans' },
|
||||
{ href: '/customers', label: 'Kunder', icon: Users, group: 'finans' },
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
'use client'
|
||||
|
||||
import { Card, CardContent } from '@/components/ui/card'
|
||||
import { formatCurrency } from '@/lib/utils'
|
||||
import type { KPIReport } from '@/types'
|
||||
|
||||
interface KPIHeroCardsProps {
|
||||
report: KPIReport
|
||||
}
|
||||
|
||||
export function KPIHeroCards({ report }: KPIHeroCardsProps) {
|
||||
return (
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
|
||||
{/* Gross margin */}
|
||||
<Card>
|
||||
<CardContent className="p-5">
|
||||
<p className="text-xs text-muted-foreground mb-1">Bruttomarginal</p>
|
||||
<p className="font-display text-xl tabular-nums tracking-tight">
|
||||
{report.grossMargin !== null ? `${report.grossMargin}%` : '—'}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground mt-1">av intäkter</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Net result */}
|
||||
<Card>
|
||||
<CardContent className="p-5">
|
||||
<p className="text-xs text-muted-foreground mb-1">Resultat</p>
|
||||
<p className={`font-display text-xl tabular-nums tracking-tight ${
|
||||
report.netResult >= 0 ? 'text-[hsl(var(--chart-1))]' : 'text-[hsl(var(--chart-2))]'
|
||||
}`}>
|
||||
{formatCurrency(report.netResult)}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground mt-1">netto</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Cash position */}
|
||||
<Card>
|
||||
<CardContent className="p-5">
|
||||
<p className="text-xs text-muted-foreground mb-1">Kassa</p>
|
||||
<p className={`font-display text-xl tabular-nums tracking-tight ${
|
||||
report.cashPosition > 0 ? 'text-[hsl(var(--chart-1))]' : 'text-[hsl(var(--chart-2))]'
|
||||
}`}>
|
||||
{formatCurrency(report.cashPosition)}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground mt-1">likvida medel</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Outstanding receivables */}
|
||||
<Card>
|
||||
<CardContent className="p-5">
|
||||
<p className="text-xs text-muted-foreground mb-1">Kundfordringar</p>
|
||||
<p className="font-display text-xl tabular-nums tracking-tight">
|
||||
{formatCurrency(report.outstandingReceivables)}
|
||||
</p>
|
||||
{report.overdueReceivables > 0 ? (
|
||||
<p className="text-xs text-[hsl(var(--chart-2))] mt-1">
|
||||
varav förfallet: {formatCurrency(report.overdueReceivables)}
|
||||
</p>
|
||||
) : (
|
||||
<p className="text-xs text-muted-foreground mt-1">utestående</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
'use client'
|
||||
|
||||
import { Card, CardContent } from '@/components/ui/card'
|
||||
import { TrendingUp, TrendingDown, Info } from 'lucide-react'
|
||||
import { formatCurrency } from '@/lib/utils'
|
||||
import type { KPIReport } from '@/types'
|
||||
|
||||
interface KPIOperationalGridProps {
|
||||
report: KPIReport
|
||||
}
|
||||
|
||||
export function KPIOperationalGrid({ report }: KPIOperationalGridProps) {
|
||||
return (
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
{/* Revenue growth */}
|
||||
<Card>
|
||||
<CardContent className="p-5">
|
||||
<p className="text-xs text-muted-foreground mb-1">Intäktstillväxt</p>
|
||||
{!report.periodComplete ? (
|
||||
<p className="text-sm text-muted-foreground">Välj ett avslutat räkenskapsår</p>
|
||||
) : report.revenueGrowth !== null ? (
|
||||
<div className="flex items-center gap-2">
|
||||
{report.revenueGrowth >= 0 ? (
|
||||
<TrendingUp className="h-4 w-4 text-[hsl(var(--chart-1))]" />
|
||||
) : (
|
||||
<TrendingDown className="h-4 w-4 text-[hsl(var(--chart-2))]" />
|
||||
)}
|
||||
<p className={`font-display text-xl tabular-nums tracking-tight ${
|
||||
report.revenueGrowth >= 0 ? 'text-[hsl(var(--chart-1))]' : 'text-[hsl(var(--chart-2))]'
|
||||
}`}>
|
||||
{report.revenueGrowth > 0 ? '+' : ''}{report.revenueGrowth}%
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-sm text-muted-foreground">Första räkenskapsåret</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Expense ratio */}
|
||||
<Card>
|
||||
<CardContent className="p-5">
|
||||
<p className="text-xs text-muted-foreground mb-1">Kostnadsandel</p>
|
||||
{report.expenseRatio !== null ? (
|
||||
<>
|
||||
<p className="font-display text-xl tabular-nums tracking-tight">
|
||||
{report.expenseRatio}%
|
||||
</p>
|
||||
<div className="mt-2 h-1.5 rounded-full bg-muted overflow-hidden">
|
||||
<div
|
||||
className="h-full rounded-full bg-[hsl(var(--chart-2))]/60 transition-all"
|
||||
style={{ width: `${Math.min(report.expenseRatio, 100)}%` }}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<p className="text-sm text-muted-foreground">Inga intäkter</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Avg payment days */}
|
||||
<Card>
|
||||
<CardContent className="p-5">
|
||||
<div className="flex items-center gap-1.5 mb-1">
|
||||
<p className="text-xs text-muted-foreground">Snittbetaltid</p>
|
||||
{report.avgPaymentDays === null && (
|
||||
<span title="Kräver minst 5 betalda fakturor med betalningsdatum. Sätts via fakturering i gnubok eller bankmatchning.">
|
||||
<Info className="h-3 w-3 text-muted-foreground/60" />
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{report.avgPaymentDays !== null ? (
|
||||
<p className="font-display text-xl tabular-nums tracking-tight">
|
||||
{report.avgPaymentDays} <span className="text-sm font-normal text-muted-foreground">dagar</span>
|
||||
</p>
|
||||
) : (
|
||||
<p className="text-sm text-muted-foreground">Inte tillräckligt med data</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* VAT liability */}
|
||||
<Card>
|
||||
<CardContent className="p-5">
|
||||
<p className="text-xs text-muted-foreground mb-1">Momsskuld</p>
|
||||
<p className={`font-display text-xl tabular-nums tracking-tight ${
|
||||
report.vatLiability > 0 ? 'text-[hsl(var(--chart-2))]' : 'text-[hsl(var(--chart-1))]'
|
||||
}`}>
|
||||
{formatCurrency(Math.abs(report.vatLiability))}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
{report.vatLiability > 0 ? 'Att betala' : report.vatLiability < 0 ? 'Att återfå' : 'Jämnt'}
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
'use client'
|
||||
|
||||
import {
|
||||
Area,
|
||||
XAxis,
|
||||
YAxis,
|
||||
CartesianGrid,
|
||||
Tooltip,
|
||||
ResponsiveContainer,
|
||||
Legend,
|
||||
Line,
|
||||
ComposedChart,
|
||||
} from 'recharts'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { formatCurrency } from '@/lib/utils'
|
||||
|
||||
interface KPITrendChartProps {
|
||||
months: { label: string; income: number; expenses: number; net: number }[]
|
||||
}
|
||||
|
||||
export function KPITrendChart({ months }: KPITrendChartProps) {
|
||||
if (months.length === 0) return null
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-base">Intäkter, kostnader & resultat per månad</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<ResponsiveContainer width="100%" height={300}>
|
||||
<ComposedChart
|
||||
data={months}
|
||||
margin={{ top: 5, right: 10, left: 10, bottom: 5 }}
|
||||
>
|
||||
<CartesianGrid strokeDasharray="3 3" vertical={false} />
|
||||
<XAxis dataKey="label" tick={{ fontSize: 12 }} />
|
||||
<YAxis
|
||||
tickFormatter={(v) =>
|
||||
new Intl.NumberFormat('sv-SE', { notation: 'compact' }).format(v)
|
||||
}
|
||||
tick={{ fontSize: 11 }}
|
||||
/>
|
||||
<Tooltip
|
||||
formatter={(value, name) => [
|
||||
formatCurrency(Number(value)),
|
||||
name === 'income'
|
||||
? 'Intäkter'
|
||||
: name === 'expenses'
|
||||
? 'Kostnader'
|
||||
: 'Resultat',
|
||||
]}
|
||||
contentStyle={{
|
||||
fontSize: '12px',
|
||||
borderRadius: '8px',
|
||||
border: '1px solid hsl(var(--border))',
|
||||
backgroundColor: 'hsl(var(--card))',
|
||||
}}
|
||||
/>
|
||||
<Legend
|
||||
formatter={(value: string) =>
|
||||
value === 'income'
|
||||
? 'Intäkter'
|
||||
: value === 'expenses'
|
||||
? 'Kostnader'
|
||||
: 'Resultat'
|
||||
}
|
||||
/>
|
||||
<Area
|
||||
type="monotone"
|
||||
dataKey="income"
|
||||
fill="hsl(var(--chart-1))"
|
||||
fillOpacity={0.15}
|
||||
stroke="hsl(var(--chart-1))"
|
||||
strokeWidth={1.5}
|
||||
/>
|
||||
<Area
|
||||
type="monotone"
|
||||
dataKey="expenses"
|
||||
fill="hsl(var(--chart-2))"
|
||||
fillOpacity={0.15}
|
||||
stroke="hsl(var(--chart-2))"
|
||||
strokeWidth={1.5}
|
||||
/>
|
||||
<Line
|
||||
type="monotone"
|
||||
dataKey="net"
|
||||
stroke="hsl(var(--chart-3))"
|
||||
strokeWidth={2}
|
||||
dot={false}
|
||||
/>
|
||||
</ComposedChart>
|
||||
</ResponsiveContainer>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,305 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect, useCallback } from 'react'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { Loader2, Plus, Copy, Check, Trash2, Key } from 'lucide-react'
|
||||
|
||||
interface ApiKey {
|
||||
id: string
|
||||
key_prefix: string
|
||||
name: string
|
||||
scopes: string[] | null
|
||||
rate_limit_rpm: number
|
||||
last_used_at: string | null
|
||||
revoked_at: string | null
|
||||
created_at: string
|
||||
}
|
||||
|
||||
export function ApiKeysPanel() {
|
||||
const { toast } = useToast()
|
||||
|
||||
const [keys, setKeys] = useState<ApiKey[]>([])
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [isCreating, setIsCreating] = useState(false)
|
||||
const [showCreateDialog, setShowCreateDialog] = useState(false)
|
||||
const [showKeyDialog, setShowKeyDialog] = useState(false)
|
||||
const [newKeyName, setNewKeyName] = useState('')
|
||||
const [newKeyValue, setNewKeyValue] = useState('')
|
||||
const [copied, setCopied] = useState(false)
|
||||
const [revokingId, setRevokingId] = useState<string | null>(null)
|
||||
|
||||
const fetchKeys = useCallback(async () => {
|
||||
try {
|
||||
const res = await fetch('/api/settings/api-keys')
|
||||
const json = await res.json()
|
||||
if (json.data) {
|
||||
setKeys(json.data.filter((k: ApiKey) => !k.revoked_at))
|
||||
}
|
||||
} catch {
|
||||
toast({ title: 'Fel', description: 'Kunde inte hämta API-nycklar', variant: 'destructive' })
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}, [toast])
|
||||
|
||||
useEffect(() => {
|
||||
fetchKeys()
|
||||
}, [fetchKeys])
|
||||
|
||||
async function handleCreate() {
|
||||
setIsCreating(true)
|
||||
try {
|
||||
const res = await fetch('/api/settings/api-keys', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: newKeyName || 'MCP-nyckel' }),
|
||||
})
|
||||
const json = await res.json()
|
||||
|
||||
if (!res.ok) {
|
||||
toast({ title: 'Fel', description: json.error, variant: 'destructive' })
|
||||
return
|
||||
}
|
||||
|
||||
setNewKeyValue(json.data.key)
|
||||
setShowCreateDialog(false)
|
||||
setShowKeyDialog(true)
|
||||
setNewKeyName('')
|
||||
fetchKeys()
|
||||
} catch {
|
||||
toast({ title: 'Fel', description: 'Kunde inte skapa nyckel', variant: 'destructive' })
|
||||
} finally {
|
||||
setIsCreating(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function handleRevoke(id: string) {
|
||||
setRevokingId(id)
|
||||
try {
|
||||
await fetch(`/api/settings/api-keys/${id}`, { method: 'DELETE' })
|
||||
setKeys((prev) => prev.filter((k) => k.id !== id))
|
||||
toast({ title: 'Nyckel återkallad' })
|
||||
} catch {
|
||||
toast({ title: 'Fel', description: 'Kunde inte återkalla nyckel', variant: 'destructive' })
|
||||
} finally {
|
||||
setRevokingId(null)
|
||||
}
|
||||
}
|
||||
|
||||
function handleCopy() {
|
||||
navigator.clipboard.writeText(newKeyValue)
|
||||
setCopied(true)
|
||||
setTimeout(() => setCopied(false), 2000)
|
||||
}
|
||||
|
||||
function formatDate(iso: string | null) {
|
||||
if (!iso) return '—'
|
||||
return new Date(iso).toLocaleDateString('sv-SE', {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
})
|
||||
}
|
||||
|
||||
const mcpUrl = typeof window !== 'undefined'
|
||||
? `${window.location.origin}/api/extensions/ext/mcp-server/mcp`
|
||||
: '/api/extensions/ext/mcp-server/mcp'
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<CardTitle>API-nycklar</CardTitle>
|
||||
<CardDescription>
|
||||
Hantera nycklar för MCP-klienter (Claude, Cursor) och andra integrationer.
|
||||
</CardDescription>
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => setShowCreateDialog(true)}
|
||||
disabled={keys.length >= 10}
|
||||
>
|
||||
<Plus className="mr-1.5 h-3.5 w-3.5" />
|
||||
Skapa nyckel
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{isLoading ? (
|
||||
<div className="flex items-center justify-center py-8">
|
||||
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
) : keys.length === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center py-8 text-center">
|
||||
<Key className="h-8 w-8 text-muted-foreground/50 mb-3" />
|
||||
<p className="text-sm text-muted-foreground">Inga API-nycklar ännu.</p>
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
Skapa en nyckel för att koppla din MCP-klient.
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{keys.map((key) => (
|
||||
<div
|
||||
key={key.id}
|
||||
className="flex items-center justify-between rounded-md border px-4 py-3"
|
||||
>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<p className="text-sm font-medium truncate">{key.name}</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-3 mt-1">
|
||||
<code className="text-xs text-muted-foreground font-mono">
|
||||
{key.key_prefix}...
|
||||
</code>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
Skapad {formatDate(key.created_at)}
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{key.last_used_at
|
||||
? `Använd ${formatDate(key.last_used_at)}`
|
||||
: 'Aldrig använd'}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => handleRevoke(key.id)}
|
||||
disabled={revokingId === key.id}
|
||||
className="text-destructive hover:text-destructive"
|
||||
>
|
||||
{revokingId === key.id ? (
|
||||
<Loader2 className="h-3.5 w-3.5 animate-spin" />
|
||||
) : (
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">Anslut MCP-klient</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
<div>
|
||||
<p className="text-sm font-medium mb-1">Claude Desktop</p>
|
||||
<p className="text-xs text-muted-foreground mb-2">
|
||||
Inställningar → Connectors → Add custom connector. Klistra in URL:en nedan.
|
||||
Du loggas in automatiskt via OAuth.
|
||||
</p>
|
||||
<pre className="rounded-md bg-muted p-3 text-xs font-mono overflow-x-auto select-all">
|
||||
{mcpUrl}
|
||||
</pre>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p className="text-sm font-medium mb-1">Claude Code / Cursor</p>
|
||||
<p className="text-xs text-muted-foreground mb-2">
|
||||
Kör i terminalen med en API-nyckel:
|
||||
</p>
|
||||
<pre className="rounded-md bg-muted p-4 text-xs font-mono overflow-x-auto">
|
||||
{`claude mcp add gnubok --transport http \\
|
||||
--url ${mcpUrl} \\
|
||||
--header "Authorization: Bearer gnubok_sk_..."`}
|
||||
</pre>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Create key dialog */}
|
||||
<Dialog open={showCreateDialog} onOpenChange={setShowCreateDialog}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Skapa API-nyckel</DialogTitle>
|
||||
<DialogDescription>
|
||||
Ge nyckeln ett namn så du vet vad den används till.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="space-y-3">
|
||||
<Label htmlFor="key-name">Namn</Label>
|
||||
<Input
|
||||
id="key-name"
|
||||
placeholder="t.ex. Claude Desktop"
|
||||
value={newKeyName}
|
||||
onChange={(e) => setNewKeyName(e.target.value)}
|
||||
onKeyDown={(e) => e.key === 'Enter' && handleCreate()}
|
||||
/>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setShowCreateDialog(false)}>
|
||||
Avbryt
|
||||
</Button>
|
||||
<Button onClick={handleCreate} disabled={isCreating}>
|
||||
{isCreating && <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />}
|
||||
Skapa
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Show key once dialog */}
|
||||
<Dialog open={showKeyDialog} onOpenChange={(open) => {
|
||||
if (!open) {
|
||||
setNewKeyValue('')
|
||||
setCopied(false)
|
||||
}
|
||||
setShowKeyDialog(open)
|
||||
}}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Din nya API-nyckel</DialogTitle>
|
||||
<DialogDescription>
|
||||
Kopiera nyckeln nu. Den visas bara en gång.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="relative">
|
||||
<code className="block rounded-md bg-muted p-4 pr-12 text-sm font-mono break-all">
|
||||
{newKeyValue}
|
||||
</code>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="absolute right-2 top-2"
|
||||
onClick={handleCopy}
|
||||
>
|
||||
{copied ? (
|
||||
<Check className="h-4 w-4 text-green-600" />
|
||||
) : (
|
||||
<Copy className="h-4 w-4" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button onClick={() => {
|
||||
setShowKeyDialog(false)
|
||||
setNewKeyValue('')
|
||||
setCopied(false)
|
||||
}}>
|
||||
Klar
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1 +1 @@
|
||||
{"$schema":"./extensions.schema.json","extensions":["enable-banking","email","arcim-migration","tic"]}
|
||||
{"$schema":"./extensions.schema.json","extensions":["enable-banking","email","arcim-migration","tic","mcp-server"]}
|
||||
|
||||
@@ -25,7 +25,8 @@
|
||||
"enable-banking",
|
||||
"email",
|
||||
"arcim-migration",
|
||||
"tic"
|
||||
"tic",
|
||||
"mcp-server"
|
||||
]
|
||||
},
|
||||
"description": "Extension IDs to enable. Each ID must match a manifest.json in the extensions/ directory."
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import type { Extension } from '@/lib/extensions/types'
|
||||
import { handleMcpRequest } from './server'
|
||||
|
||||
export const mcpServerExtension: Extension = {
|
||||
id: 'mcp-server',
|
||||
name: 'MCP Server',
|
||||
version: '1.0.0',
|
||||
|
||||
settingsPanel: {
|
||||
label: 'MCP-server (API)',
|
||||
path: '/settings?tab=api',
|
||||
},
|
||||
|
||||
apiRoutes: [
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/mcp',
|
||||
skipAuth: true, // Auth handled via API key in the handler
|
||||
handler: handleMcpRequest,
|
||||
},
|
||||
// MCP Streamable HTTP also needs GET for SSE and DELETE for session termination
|
||||
{
|
||||
method: 'GET',
|
||||
path: '/mcp',
|
||||
skipAuth: true,
|
||||
handler: async () => {
|
||||
const appUrl = process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000'
|
||||
return new Response('Authorization required', {
|
||||
status: 401,
|
||||
headers: {
|
||||
'WWW-Authenticate': `Bearer resource_metadata="${appUrl}/.well-known/oauth-protected-resource"`,
|
||||
},
|
||||
})
|
||||
},
|
||||
},
|
||||
{
|
||||
method: 'DELETE',
|
||||
path: '/mcp',
|
||||
skipAuth: true,
|
||||
handler: async () => new Response(null, { status: 204 }), // Stateless — no sessions to terminate
|
||||
},
|
||||
],
|
||||
|
||||
eventHandlers: [],
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"id": "mcp-server",
|
||||
"sector": "general",
|
||||
"exportName": "mcpServerExtension",
|
||||
"entryPoint": "@/extensions/general/mcp-server",
|
||||
"requiredEnvVars": [],
|
||||
"optionalEnvVars": [],
|
||||
"npmDependencies": [],
|
||||
"definition": {
|
||||
"name": "MCP-server (API)",
|
||||
"category": "operations",
|
||||
"icon": "Terminal",
|
||||
"dataPattern": "manual",
|
||||
"hasOwnData": false,
|
||||
"description": "Gör bokföring via Claude, Cursor eller annan MCP-klient",
|
||||
"longDescription": "Exponerar gnuboks bokföringsmotor som MCP-verktyg (Model Context Protocol). Koppla din MCP-klient med en API-nyckel och gör bokföring genom konversation: visa okategoriserade transaktioner, bokför dem, skapa fakturor."
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,65 @@
|
||||
import crypto from 'crypto'
|
||||
import { createClient } from '@supabase/supabase-js'
|
||||
|
||||
const KEY_PREFIX = 'gnubok_sk_'
|
||||
|
||||
/**
|
||||
* Create a Supabase service client that doesn't require cookies.
|
||||
* Used for API key validation (MCP, webhooks) where there's no browser session.
|
||||
*/
|
||||
export function createServiceClientNoCookies() {
|
||||
return createClient(
|
||||
process.env.NEXT_PUBLIC_SUPABASE_URL!,
|
||||
process.env.SUPABASE_SERVICE_ROLE_KEY!
|
||||
)
|
||||
}
|
||||
|
||||
export function generateApiKey(): { key: string; hash: string; prefix: string } {
|
||||
const random = crypto.randomBytes(32).toString('base64url')
|
||||
const key = `${KEY_PREFIX}${random}`
|
||||
const hash = hashApiKey(key)
|
||||
const prefix = key.slice(0, KEY_PREFIX.length + 8)
|
||||
return { key, hash, prefix }
|
||||
}
|
||||
|
||||
export function hashApiKey(key: string): string {
|
||||
return crypto.createHash('sha256').update(key).digest('hex')
|
||||
}
|
||||
|
||||
export function extractBearerToken(request: Request): string | null {
|
||||
const authHeader = request.headers.get('authorization')
|
||||
if (!authHeader?.startsWith('Bearer ')) return null
|
||||
return authHeader.slice(7)
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate an API key and enforce rate limiting.
|
||||
* Uses the DB RPC for atomic check + increment.
|
||||
* Returns the user_id on success, or an error with HTTP status.
|
||||
*/
|
||||
export async function validateApiKey(
|
||||
key: string
|
||||
): Promise<{ userId: string } | { error: string; status: number }> {
|
||||
if (!key.startsWith(KEY_PREFIX)) {
|
||||
return { error: 'Invalid API key format', status: 401 }
|
||||
}
|
||||
|
||||
const hash = hashApiKey(key)
|
||||
const supabase = createServiceClientNoCookies()
|
||||
|
||||
const { data, error } = await supabase.rpc('validate_and_increment_api_key', {
|
||||
p_key_hash: hash,
|
||||
})
|
||||
|
||||
if (error || !data || data.length === 0) {
|
||||
return { error: 'Invalid API key', status: 401 }
|
||||
}
|
||||
|
||||
const row = data[0]
|
||||
|
||||
if (row.rate_limited) {
|
||||
return { error: 'Rate limit exceeded', status: 429 }
|
||||
}
|
||||
|
||||
return { userId: row.user_id }
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import crypto from 'crypto'
|
||||
|
||||
/**
|
||||
* Stateless OAuth auth codes.
|
||||
* The auth code is an AES-256-GCM encrypted JSON payload containing
|
||||
* the user ID, PKCE code_challenge, and expiry.
|
||||
*
|
||||
* The API key is NOT embedded — it gets created at token exchange
|
||||
* after PKCE verification, preventing orphaned keys.
|
||||
*/
|
||||
|
||||
const ALGORITHM = 'aes-256-gcm'
|
||||
const CODE_TTL_MS = 5 * 60 * 1000 // 5 minutes
|
||||
|
||||
function getEncryptionKey(): Buffer {
|
||||
const secret = process.env.SUPABASE_SERVICE_ROLE_KEY
|
||||
if (!secret) throw new Error('SUPABASE_SERVICE_ROLE_KEY is required')
|
||||
return crypto.createHash('sha256').update(secret).digest()
|
||||
}
|
||||
|
||||
export interface AuthCodePayload {
|
||||
userId: string
|
||||
codeChallenge: string
|
||||
codeChallengeMethod: string
|
||||
redirectUri: string
|
||||
exp: number
|
||||
}
|
||||
|
||||
export function createAuthCode(payload: Omit<AuthCodePayload, 'exp'>): string {
|
||||
const data: AuthCodePayload = {
|
||||
...payload,
|
||||
exp: Date.now() + CODE_TTL_MS,
|
||||
}
|
||||
|
||||
const key = getEncryptionKey()
|
||||
const iv = crypto.randomBytes(12)
|
||||
const cipher = crypto.createCipheriv(ALGORITHM, key, iv)
|
||||
|
||||
const json = JSON.stringify(data)
|
||||
const encrypted = Buffer.concat([cipher.update(json, 'utf8'), cipher.final()])
|
||||
const tag = cipher.getAuthTag()
|
||||
|
||||
const combined = Buffer.concat([iv, tag, encrypted])
|
||||
return combined.toString('base64url')
|
||||
}
|
||||
|
||||
export function decryptAuthCode(code: string): AuthCodePayload | null {
|
||||
try {
|
||||
const key = getEncryptionKey()
|
||||
const combined = Buffer.from(code, 'base64url')
|
||||
|
||||
const iv = combined.subarray(0, 12)
|
||||
const tag = combined.subarray(12, 28)
|
||||
const encrypted = combined.subarray(28)
|
||||
|
||||
const decipher = crypto.createDecipheriv(ALGORITHM, key, iv)
|
||||
decipher.setAuthTag(tag)
|
||||
|
||||
const decrypted = Buffer.concat([decipher.update(encrypted), decipher.final()])
|
||||
const payload: AuthCodePayload = JSON.parse(decrypted.toString('utf8'))
|
||||
|
||||
if (Date.now() > payload.exp) return null
|
||||
|
||||
return payload
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify PKCE: SHA256(code_verifier) must equal the stored code_challenge.
|
||||
* Only S256 is supported (plain is insecure and not advertised).
|
||||
*/
|
||||
export function verifyPkce(
|
||||
codeVerifier: string,
|
||||
codeChallenge: string
|
||||
): boolean {
|
||||
const hash = crypto
|
||||
.createHash('sha256')
|
||||
.update(codeVerifier)
|
||||
.digest('base64url')
|
||||
return hash === codeChallenge
|
||||
}
|
||||
|
||||
/**
|
||||
* Hash an auth code for replay tracking.
|
||||
*/
|
||||
export function hashAuthCode(code: string): string {
|
||||
return crypto.createHash('sha256').update(code).digest('hex')
|
||||
}
|
||||
@@ -49,7 +49,7 @@ describe('sectors registry', () => {
|
||||
})
|
||||
|
||||
it('should have 8 total extensions', () => {
|
||||
expect(getAllExtensions().length).toBe(10)
|
||||
expect(getAllExtensions().length).toBe(11)
|
||||
})
|
||||
|
||||
it('should have unique slugs within each sector', () => {
|
||||
@@ -94,7 +94,7 @@ describe('sectors registry', () => {
|
||||
|
||||
it('getExtensionsBySector returns extensions for a sector', () => {
|
||||
const extensions = getExtensionsBySector('general')
|
||||
expect(extensions.length).toBe(10)
|
||||
expect(extensions.length).toBe(11)
|
||||
})
|
||||
|
||||
it('all extensions have required fields', () => {
|
||||
|
||||
@@ -5,4 +5,5 @@ export const ENABLED_EXTENSION_IDS: ReadonlySet<string> = new Set([
|
||||
'email',
|
||||
'arcim-migration',
|
||||
'tic',
|
||||
'mcp-server',
|
||||
])
|
||||
|
||||
@@ -4,10 +4,12 @@ import { enableBankingExtension } from '@/extensions/general/enable-banking'
|
||||
import { emailExtension } from '@/extensions/general/email'
|
||||
import { arcimMigrationExtension } from '@/extensions/general/arcim-migration'
|
||||
import { ticExtension } from '@/extensions/general/tic'
|
||||
import { mcpServerExtension } from '@/extensions/general/mcp-server'
|
||||
|
||||
export const FIRST_PARTY_EXTENSIONS: Extension[] = [
|
||||
enableBankingExtension,
|
||||
emailExtension,
|
||||
arcimMigrationExtension,
|
||||
ticExtension,
|
||||
mcpServerExtension,
|
||||
]
|
||||
|
||||
@@ -58,5 +58,15 @@ export const EXTENSION_DEFINITIONS: Record<string, ExtensionDefinition[]> = {
|
||||
"order": 10
|
||||
}
|
||||
},
|
||||
{
|
||||
"slug": "mcp-server",
|
||||
"name": "MCP-server (API)",
|
||||
"sector": "general",
|
||||
"category": "operations",
|
||||
"icon": "Terminal",
|
||||
"dataPattern": "manual",
|
||||
"description": "Gör bokföring via Claude, Cursor eller annan MCP-klient",
|
||||
"longDescription": "Exponerar gnuboks bokföringsmotor som MCP-verktyg (Model Context Protocol). Koppla din MCP-klient med en API-nyckel och gör bokföring genom konversation: visa okategoriserade transaktioner, bokför dem, skapa fakturor."
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
calculateGrossMargin,
|
||||
calculateCashPosition,
|
||||
calculateRevenueGrowth,
|
||||
calculateExpenseRatio,
|
||||
calculateAvgPaymentDays,
|
||||
} from '../kpi'
|
||||
import type { IncomeStatementReport, TrialBalanceRow } from '@/types'
|
||||
|
||||
function makeIncomeStatement(
|
||||
overrides: Partial<IncomeStatementReport> = {}
|
||||
): IncomeStatementReport {
|
||||
return {
|
||||
revenue_sections: [],
|
||||
total_revenue: 100000,
|
||||
expense_sections: [],
|
||||
total_expenses: 60000,
|
||||
financial_sections: [],
|
||||
total_financial: 0,
|
||||
net_result: 40000,
|
||||
period: { start: '2025-01-01', end: '2025-12-31' },
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
function makeTrialBalanceRow(
|
||||
overrides: Partial<TrialBalanceRow> = {}
|
||||
): TrialBalanceRow {
|
||||
return {
|
||||
account_number: '1930',
|
||||
account_name: 'Företagskonto',
|
||||
account_class: 1,
|
||||
opening_debit: 0,
|
||||
opening_credit: 0,
|
||||
period_debit: 0,
|
||||
period_credit: 0,
|
||||
closing_debit: 0,
|
||||
closing_credit: 0,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe('calculateGrossMargin', () => {
|
||||
it('returns margin when revenue and COGS exist', () => {
|
||||
const stmt = makeIncomeStatement({
|
||||
total_revenue: 200000,
|
||||
expense_sections: [
|
||||
{
|
||||
title: 'Varor och material',
|
||||
rows: [{ account_number: '4010', account_name: 'Inköp', amount: 80000 }],
|
||||
subtotal: 80000,
|
||||
},
|
||||
{
|
||||
title: 'Lokalkostnader',
|
||||
rows: [{ account_number: '5010', account_name: 'Hyra', amount: 20000 }],
|
||||
subtotal: 20000,
|
||||
},
|
||||
],
|
||||
})
|
||||
// (200000 - 80000) / 200000 * 100 = 60%
|
||||
expect(calculateGrossMargin(stmt)).toBe(60)
|
||||
})
|
||||
|
||||
it('returns null when total_revenue is 0', () => {
|
||||
const stmt = makeIncomeStatement({ total_revenue: 0 })
|
||||
expect(calculateGrossMargin(stmt)).toBeNull()
|
||||
})
|
||||
|
||||
it('returns 100% when no class 4 expenses', () => {
|
||||
const stmt = makeIncomeStatement({
|
||||
total_revenue: 50000,
|
||||
expense_sections: [
|
||||
{
|
||||
title: 'Lokalkostnader',
|
||||
rows: [{ account_number: '5010', account_name: 'Hyra', amount: 10000 }],
|
||||
subtotal: 10000,
|
||||
},
|
||||
],
|
||||
})
|
||||
expect(calculateGrossMargin(stmt)).toBe(100)
|
||||
})
|
||||
})
|
||||
|
||||
describe('calculateCashPosition', () => {
|
||||
it('sums closing balances for 19xx accounts', () => {
|
||||
const rows = [
|
||||
makeTrialBalanceRow({ account_number: '1930', closing_debit: 50000, closing_credit: 0 }),
|
||||
makeTrialBalanceRow({ account_number: '1931', closing_debit: 10000, closing_credit: 0 }),
|
||||
makeTrialBalanceRow({ account_number: '1510', closing_debit: 25000, closing_credit: 0 }),
|
||||
]
|
||||
// Only 1930 + 1931 = 60000
|
||||
expect(calculateCashPosition(rows)).toBe(60000)
|
||||
})
|
||||
|
||||
it('returns 0 for empty rows', () => {
|
||||
expect(calculateCashPosition([])).toBe(0)
|
||||
})
|
||||
|
||||
it('handles credit balances on 19xx accounts', () => {
|
||||
const rows = [
|
||||
makeTrialBalanceRow({ account_number: '1930', closing_debit: 0, closing_credit: 5000 }),
|
||||
]
|
||||
expect(calculateCashPosition(rows)).toBe(-5000)
|
||||
})
|
||||
})
|
||||
|
||||
describe('calculateRevenueGrowth', () => {
|
||||
it('returns positive growth', () => {
|
||||
// (120000 - 100000) / 100000 * 100 = 20%
|
||||
expect(calculateRevenueGrowth(120000, 100000)).toBe(20)
|
||||
})
|
||||
|
||||
it('returns negative growth (decline)', () => {
|
||||
// (80000 - 100000) / 100000 * 100 = -20%
|
||||
expect(calculateRevenueGrowth(80000, 100000)).toBe(-20)
|
||||
})
|
||||
|
||||
it('returns null when previous revenue is null', () => {
|
||||
expect(calculateRevenueGrowth(100000, null)).toBeNull()
|
||||
})
|
||||
|
||||
it('returns null when previous revenue is 0', () => {
|
||||
expect(calculateRevenueGrowth(100000, 0)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('calculateExpenseRatio', () => {
|
||||
it('returns ratio for normal data', () => {
|
||||
const stmt = makeIncomeStatement({ total_revenue: 200000, total_expenses: 120000 })
|
||||
// 120000 / 200000 * 100 = 60%
|
||||
expect(calculateExpenseRatio(stmt)).toBe(60)
|
||||
})
|
||||
|
||||
it('returns null when total_revenue is 0', () => {
|
||||
const stmt = makeIncomeStatement({ total_revenue: 0, total_expenses: 5000 })
|
||||
expect(calculateExpenseRatio(stmt)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('calculateAvgPaymentDays', () => {
|
||||
it('returns average for >= 5 invoices', () => {
|
||||
const invoices = [
|
||||
{ invoice_date: '2025-01-01', paid_at: '2025-01-11' }, // 10 days
|
||||
{ invoice_date: '2025-02-01', paid_at: '2025-02-21' }, // 20 days
|
||||
{ invoice_date: '2025-03-01', paid_at: '2025-03-16' }, // 15 days
|
||||
{ invoice_date: '2025-04-01', paid_at: '2025-04-26' }, // 25 days
|
||||
{ invoice_date: '2025-05-01', paid_at: '2025-05-31' }, // 30 days
|
||||
]
|
||||
// avg = (10+20+15+25+30) / 5 = 20
|
||||
expect(calculateAvgPaymentDays(invoices)).toBe(20)
|
||||
})
|
||||
|
||||
it('returns null for fewer than 5 invoices', () => {
|
||||
const invoices = [
|
||||
{ invoice_date: '2025-01-01', paid_at: '2025-01-11' },
|
||||
{ invoice_date: '2025-02-01', paid_at: '2025-02-21' },
|
||||
]
|
||||
expect(calculateAvgPaymentDays(invoices)).toBeNull()
|
||||
})
|
||||
|
||||
it('returns null for empty array', () => {
|
||||
expect(calculateAvgPaymentDays([])).toBeNull()
|
||||
})
|
||||
|
||||
it('clamps negative days to 0', () => {
|
||||
const invoices = [
|
||||
{ invoice_date: '2025-01-10', paid_at: '2025-01-05' }, // would be -5, clamped to 0
|
||||
{ invoice_date: '2025-02-01', paid_at: '2025-02-11' }, // 10
|
||||
{ invoice_date: '2025-03-01', paid_at: '2025-03-11' }, // 10
|
||||
{ invoice_date: '2025-04-01', paid_at: '2025-04-11' }, // 10
|
||||
{ invoice_date: '2025-05-01', paid_at: '2025-05-11' }, // 10
|
||||
]
|
||||
// avg = (0+10+10+10+10) / 5 = 8
|
||||
expect(calculateAvgPaymentDays(invoices)).toBe(8)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,74 @@
|
||||
import type { IncomeStatementReport, TrialBalanceRow } from '@/types'
|
||||
|
||||
/**
|
||||
* Calculate gross margin from income statement.
|
||||
* Gross margin = (revenue - COGS) / revenue × 100
|
||||
* COGS = class 4 expense sections (Varor och material, etc.)
|
||||
*/
|
||||
export function calculateGrossMargin(incomeStatement: IncomeStatementReport): number | null {
|
||||
const { total_revenue, expense_sections } = incomeStatement
|
||||
if (total_revenue === 0) return null
|
||||
|
||||
// Class 4 expenses = cost of goods sold (account prefixes 40-49)
|
||||
const cogs = expense_sections
|
||||
.filter((s) => s.rows.some((r) => r.account_number.startsWith('4')))
|
||||
.reduce((sum, s) => sum + s.subtotal, 0)
|
||||
|
||||
return Math.round(((total_revenue - cogs) / total_revenue) * 10000) / 100
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate cash position from trial balance rows.
|
||||
* Sums closing balances for accounts matching 19xx (bank + cash accounts).
|
||||
*/
|
||||
export function calculateCashPosition(rows: TrialBalanceRow[]): number {
|
||||
const cashRows = rows.filter((r) => r.account_number.startsWith('19'))
|
||||
const total = cashRows.reduce(
|
||||
(sum, r) => sum + (r.closing_debit - r.closing_credit),
|
||||
0
|
||||
)
|
||||
return Math.round(total * 100) / 100
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate revenue growth between two periods.
|
||||
* Returns percentage or null if no previous period data.
|
||||
*/
|
||||
export function calculateRevenueGrowth(
|
||||
currentRevenue: number,
|
||||
previousRevenue: number | null
|
||||
): number | null {
|
||||
if (previousRevenue === null || previousRevenue === 0) return null
|
||||
return Math.round(((currentRevenue - previousRevenue) / previousRevenue) * 10000) / 100
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate expense ratio from income statement.
|
||||
* Expense ratio = total_expenses / total_revenue × 100
|
||||
*/
|
||||
export function calculateExpenseRatio(incomeStatement: IncomeStatementReport): number | null {
|
||||
const { total_revenue, total_expenses } = incomeStatement
|
||||
if (total_revenue === 0) return null
|
||||
return Math.round((total_expenses / total_revenue) * 10000) / 100
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate average payment days from paid invoices.
|
||||
* Returns null if fewer than 5 invoices with paid_at data.
|
||||
*/
|
||||
export function calculateAvgPaymentDays(
|
||||
paidInvoices: { invoice_date: string; paid_at: string }[]
|
||||
): number | null {
|
||||
if (paidInvoices.length < 5) return null
|
||||
|
||||
const totalDays = paidInvoices.reduce((sum, inv) => {
|
||||
const invoiceDate = new Date(inv.invoice_date)
|
||||
const paidDate = new Date(inv.paid_at)
|
||||
const days = Math.floor(
|
||||
(paidDate.getTime() - invoiceDate.getTime()) / (1000 * 60 * 60 * 24)
|
||||
)
|
||||
return sum + Math.max(0, days)
|
||||
}, 0)
|
||||
|
||||
return Math.round(totalDays / paidInvoices.length)
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Stdio-to-HTTP bridge for Claude Desktop.
|
||||
* Reads JSON-RPC from stdin, POSTs to the gnubok MCP endpoint, writes response to stdout.
|
||||
*
|
||||
* Usage in claude_desktop_config.json:
|
||||
* {
|
||||
* "mcpServers": {
|
||||
* "gnubok": {
|
||||
* "command": "node",
|
||||
* "args": ["/path/to/erp-base/scripts/mcp-bridge.mjs"],
|
||||
* "env": {
|
||||
* "GNUBOK_API_KEY": "gnubok_sk_...",
|
||||
* "GNUBOK_URL": "http://localhost:3000/api/extensions/ext/mcp-server/mcp"
|
||||
* }
|
||||
* }
|
||||
* }
|
||||
* }
|
||||
*/
|
||||
|
||||
const API_KEY = process.env.GNUBOK_API_KEY
|
||||
const URL = process.env.GNUBOK_URL || 'http://localhost:3000/api/extensions/ext/mcp-server/mcp'
|
||||
|
||||
if (!API_KEY) {
|
||||
process.stderr.write('Error: GNUBOK_API_KEY environment variable is required\n')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
let buffer = ''
|
||||
|
||||
process.stdin.setEncoding('utf8')
|
||||
process.stdin.on('data', (chunk) => {
|
||||
buffer += chunk
|
||||
|
||||
// JSON-RPC messages are newline-delimited
|
||||
let newlineIdx
|
||||
while ((newlineIdx = buffer.indexOf('\n')) !== -1) {
|
||||
const line = buffer.slice(0, newlineIdx).trim()
|
||||
buffer = buffer.slice(newlineIdx + 1)
|
||||
|
||||
if (!line) continue
|
||||
|
||||
handleMessage(line).catch((err) => {
|
||||
process.stderr.write(`Bridge error: ${err.message}\n`)
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
process.stdin.on('end', () => {
|
||||
process.exit(0)
|
||||
})
|
||||
|
||||
async function handleMessage(line) {
|
||||
let parsed
|
||||
try {
|
||||
parsed = JSON.parse(line)
|
||||
} catch {
|
||||
process.stderr.write(`Invalid JSON: ${line}\n`)
|
||||
return
|
||||
}
|
||||
|
||||
// Notifications (no id) don't expect a response, but still forward them
|
||||
const isNotification = parsed.id === undefined || parsed.id === null
|
||||
|
||||
try {
|
||||
const res = await fetch(URL, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${API_KEY}`,
|
||||
},
|
||||
body: line,
|
||||
})
|
||||
|
||||
if (res.status === 204) {
|
||||
// No content (e.g. notifications/initialized) — nothing to write back
|
||||
return
|
||||
}
|
||||
|
||||
const text = await res.text()
|
||||
if (text) {
|
||||
process.stdout.write(text + '\n')
|
||||
}
|
||||
} catch (err) {
|
||||
if (!isNotification) {
|
||||
const errorResponse = JSON.stringify({
|
||||
jsonrpc: '2.0',
|
||||
id: parsed.id,
|
||||
error: { code: -32000, message: `Bridge error: ${err.message}` },
|
||||
})
|
||||
process.stdout.write(errorResponse + '\n')
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
-- API keys for external integrations (MCP, webhooks, future public API)
|
||||
CREATE TABLE public.api_keys (
|
||||
id uuid DEFAULT gen_random_uuid() PRIMARY KEY,
|
||||
user_id uuid NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
|
||||
key_hash text NOT NULL,
|
||||
key_prefix text NOT NULL, -- e.g. "gnubok_sk_a8f2..." for display
|
||||
name text NOT NULL DEFAULT 'Unnamed key',
|
||||
scopes text[] DEFAULT NULL, -- NULL = full access. Future: ['read', 'write', 'mcp']
|
||||
rate_limit_rpm integer NOT NULL DEFAULT 100,
|
||||
request_count integer NOT NULL DEFAULT 0,
|
||||
rate_limit_window_start timestamptz,
|
||||
last_used_at timestamptz,
|
||||
revoked_at timestamptz,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
-- RLS
|
||||
ALTER TABLE public.api_keys ENABLE ROW LEVEL SECURITY;
|
||||
|
||||
CREATE POLICY "Users can view own api_keys"
|
||||
ON public.api_keys FOR SELECT USING (auth.uid() = user_id);
|
||||
CREATE POLICY "Users can insert own api_keys"
|
||||
ON public.api_keys FOR INSERT WITH CHECK (auth.uid() = user_id);
|
||||
CREATE POLICY "Users can update own api_keys"
|
||||
ON public.api_keys FOR UPDATE USING (auth.uid() = user_id);
|
||||
CREATE POLICY "Users can delete own api_keys"
|
||||
ON public.api_keys FOR DELETE USING (auth.uid() = user_id);
|
||||
|
||||
-- Indexes
|
||||
CREATE INDEX idx_api_keys_user_id ON public.api_keys (user_id);
|
||||
CREATE UNIQUE INDEX idx_api_keys_key_hash ON public.api_keys (key_hash);
|
||||
|
||||
-- Triggers
|
||||
CREATE TRIGGER set_updated_at_api_keys
|
||||
BEFORE UPDATE ON public.api_keys
|
||||
FOR EACH ROW EXECUTE FUNCTION public.update_updated_at_column();
|
||||
|
||||
CREATE TRIGGER audit_api_keys
|
||||
AFTER INSERT OR UPDATE OR DELETE ON public.api_keys
|
||||
FOR EACH ROW EXECUTE FUNCTION public.write_audit_log();
|
||||
|
||||
-- Atomic rate-limited key validation (called by service role, bypasses RLS)
|
||||
CREATE OR REPLACE FUNCTION public.validate_and_increment_api_key(p_key_hash text)
|
||||
RETURNS TABLE(user_id uuid, rate_limited boolean)
|
||||
LANGUAGE plpgsql SECURITY DEFINER AS $$
|
||||
DECLARE
|
||||
v_user_id uuid;
|
||||
v_rate_limit_rpm integer;
|
||||
v_request_count integer;
|
||||
v_window_start timestamptz;
|
||||
BEGIN
|
||||
-- Lock row for atomic update
|
||||
SELECT ak.user_id, ak.rate_limit_rpm, ak.request_count, ak.rate_limit_window_start
|
||||
INTO v_user_id, v_rate_limit_rpm, v_request_count, v_window_start
|
||||
FROM public.api_keys ak
|
||||
WHERE ak.key_hash = p_key_hash AND ak.revoked_at IS NULL
|
||||
FOR UPDATE;
|
||||
|
||||
IF v_user_id IS NULL THEN
|
||||
RETURN;
|
||||
END IF;
|
||||
|
||||
-- Reset window if expired (> 1 minute old)
|
||||
IF v_window_start IS NULL OR v_window_start < now() - interval '1 minute' THEN
|
||||
UPDATE public.api_keys
|
||||
SET request_count = 1,
|
||||
rate_limit_window_start = now(),
|
||||
last_used_at = now()
|
||||
WHERE key_hash = p_key_hash;
|
||||
|
||||
RETURN QUERY SELECT v_user_id, false;
|
||||
RETURN;
|
||||
END IF;
|
||||
|
||||
-- Check rate limit
|
||||
IF v_request_count >= v_rate_limit_rpm THEN
|
||||
RETURN QUERY SELECT v_user_id, true;
|
||||
RETURN;
|
||||
END IF;
|
||||
|
||||
-- Increment counter
|
||||
UPDATE public.api_keys
|
||||
SET request_count = request_count + 1,
|
||||
last_used_at = now()
|
||||
WHERE key_hash = p_key_hash;
|
||||
|
||||
RETURN QUERY SELECT v_user_id, false;
|
||||
END;
|
||||
$$;
|
||||
@@ -0,0 +1,9 @@
|
||||
-- Track used OAuth authorization codes to prevent replay attacks (OAuth 2.1 §4.1.2)
|
||||
-- Only accessed by service role client, no RLS needed
|
||||
CREATE TABLE public.oauth_used_codes (
|
||||
code_hash text PRIMARY KEY,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
-- Index for cleanup queries
|
||||
CREATE INDEX idx_oauth_used_codes_created_at ON public.oauth_used_codes (created_at);
|
||||
@@ -1996,3 +1996,22 @@ export interface VatBreakdownItem {
|
||||
base: number
|
||||
amount: number
|
||||
}
|
||||
|
||||
// KPI Report
|
||||
export interface KPIReport {
|
||||
grossMargin: number | null // percentage, null if no revenue
|
||||
netResult: number // SEK
|
||||
cashPosition: number // SEK (sum of 19xx account balances)
|
||||
outstandingReceivables: number // SEK
|
||||
overdueReceivables: number // SEK
|
||||
revenueGrowth: number | null // percentage, null if no prior period or current period incomplete
|
||||
expenseRatio: number | null // percentage, null if no revenue
|
||||
avgPaymentDays: number | null // days, null if < 5 paid invoices with paid_at
|
||||
paidInvoiceCount: number // how many invoices had paid_at data (for gating)
|
||||
vatLiability: number // SEK, ruta 49 (positive = owe, negative = refund)
|
||||
totalRevenue: number // SEK
|
||||
totalExpenses: number // SEK
|
||||
periodComplete: boolean // whether selected period is closed/complete
|
||||
months: { label: string; income: number; expenses: number; net: number }[]
|
||||
period: { start: string; end: string }
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user