diff --git a/.claude/skills/mcp-builder/SKILL.md b/.claude/skills/mcp-builder/SKILL.md new file mode 100644 index 00000000..8a1a77a4 --- /dev/null +++ b/.claude/skills/mcp-builder/SKILL.md @@ -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 + + + 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? + 3 + + + +``` + +--- + +# 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 diff --git a/.claude/skills/mcp-builder/reference/evaluation.md b/.claude/skills/mcp-builder/reference/evaluation.md new file mode 100644 index 00000000..87e9bb78 --- /dev/null +++ b/.claude/skills/mcp-builder/reference/evaluation.md @@ -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 + + + Your question here + Single verifiable answer + + +``` + +--- + +## 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 + + + Find the project created in Q2 2024 with the highest number of completed tasks. What is the project name? + Website Redesign + + + Search for issues labeled as "bug" that were closed in March 2024. Which user closed the most issues? Provide their username. + sarah_dev + + + 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? + 7 + + + Find the repository with the most stars that was created before 2023. What is the repository name? + data-pipeline + + +``` + +## Evaluation Examples + +### Good Questions + +**Example 1: Multi-hop question requiring deep exploration (GitHub MCP)** +```xml + + 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? + Python + +``` + +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 + + 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? + Product Manager + +``` + +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 + + 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. + alex_eng + +``` + +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 + + 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? + Healthcare + +``` + +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 + + How many open issues are currently assigned to the engineering team? + 47 + +``` + +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 + + Find the pull request with title "Add authentication feature" and tell me who created it. + developer123 + +``` + +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 + + List all the repositories that have Python as their primary language. + repo1, repo2, repo3, data-pipeline, ml-tools + +``` + +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 ``** 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 `` elements: + +```xml + + + Find the project created in Q2 2024 with the highest number of completed tasks. What is the project name? + Website Redesign + + + Search for issues labeled as "bug" that were closed in March 2024. Which user closed the most issues? Provide their username. + sarah_dev + + +``` + +## 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 + + + Find the user who created the most issues in January 2024. What is their username? + alice_developer + + + Among all pull requests merged in Q1 2024, which repository had the highest number? Provide the repository name. + backend-api + + + Find the project that was completed in December 2023 and had the longest duration from start to finish. How many days did it take? + 127 + + +``` + +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 \ No newline at end of file diff --git a/.claude/skills/mcp-builder/reference/mcp_best_practices.md b/.claude/skills/mcp-builder/reference/mcp_best_practices.md new file mode 100644 index 00000000..b9d343cc --- /dev/null +++ b/.claude/skills/mcp-builder/reference/mcp_best_practices.md @@ -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 diff --git a/.claude/skills/mcp-builder/reference/node_mcp_server.md b/.claude/skills/mcp-builder/reference/node_mcp_server.md new file mode 100644 index 00000000..f6e5df98 --- /dev/null +++ b/.claude/skills/mcp-builder/reference/node_mcp_server.md @@ -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; + +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 ''" 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( + "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) { + 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( + endpoint: string, + method: "GET" | "POST" | "PUT" | "DELETE" = "GET", + data?: any, + params?: any +): Promise { + 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 { + const response = await axios.get(`${API_URL}/resource/${resourceId}`); + return response.data; +} + +// Bad: Promise chains +function fetchData(resourceId: string): Promise { + 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; + +async function getUser(id: string): Promise { + const data = await apiCall(`/users/${id}`); + return UserSchema.parse(data); // Runtime validation +} + +// Bad: Using any +async function getUser(id: string): Promise { + 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; + +// Shared utility functions +async function makeApiRequest( + endpoint: string, + method: "GET" | "POST" | "PUT" | "DELETE" = "GET", + data?: any, + params?: any +): Promise { + 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 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 \ No newline at end of file diff --git a/.claude/skills/mcp-builder/reference/python_mcp_server.md b/.claude/skills/mcp-builder/reference/python_mcp_server.md new file mode 100644 index 00000000..cf7ec996 --- /dev/null +++ b/.claude/skills/mcp-builder/reference/python_mcp_server.md @@ -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: " or "No users found matching ''" + + 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 \ No newline at end of file diff --git a/.claude/skills/mcp-builder/scripts/connections.py b/.claude/skills/mcp-builder/scripts/connections.py new file mode 100644 index 00000000..ffcd0da3 --- /dev/null +++ b/.claude/skills/mcp-builder/scripts/connections.py @@ -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'") diff --git a/.claude/skills/mcp-builder/scripts/evaluation.py b/.claude/skills/mcp-builder/scripts/evaluation.py new file mode 100644 index 00000000..41778569 --- /dev/null +++ b/.claude/skills/mcp-builder/scripts/evaluation.py @@ -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 tags +3. Provide feedback on the tools provided, wrapped in tags +4. Provide your final response, wrapped in tags + +Summary Requirements: +- In your 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 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 tags +- If you cannot solve the task return NOT_FOUND +- 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}>(.*?)" + 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()) diff --git a/.claude/skills/mcp-builder/scripts/example_evaluation.xml b/.claude/skills/mcp-builder/scripts/example_evaluation.xml new file mode 100644 index 00000000..41e4459b --- /dev/null +++ b/.claude/skills/mcp-builder/scripts/example_evaluation.xml @@ -0,0 +1,22 @@ + + + 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)? + 11614.72 + + + 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. + 87.25 + + + A sphere has a volume of 500 cubic meters. Calculate its surface area in square meters. Round to 2 decimal places. + 304.65 + + + Calculate the population standard deviation of this dataset: [12, 15, 18, 22, 25, 30, 35]. Round to 2 decimal places. + 7.61 + + + Calculate the pH of a solution with a hydrogen ion concentration of 3.5 Γ— 10^-5 M. Round to 2 decimal places. + 4.46 + + diff --git a/.claude/skills/mcp-builder/scripts/requirements.txt b/.claude/skills/mcp-builder/scripts/requirements.txt new file mode 100644 index 00000000..e73e5d1e --- /dev/null +++ b/.claude/skills/mcp-builder/scripts/requirements.txt @@ -0,0 +1,2 @@ +anthropic>=0.39.0 +mcp>=1.1.0 diff --git a/app/(dashboard)/nyckeltal/page.tsx b/app/(dashboard)/nyckeltal/page.tsx new file mode 100644 index 00000000..d21d7183 --- /dev/null +++ b/app/(dashboard)/nyckeltal/page.tsx @@ -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([]) + const [selectedPeriod, setSelectedPeriod] = useState('') + const [report, setReport] = useState(null) + const [isLoadingInit, setIsLoadingInit] = useState(true) + const [isLoadingReport, setIsLoadingReport] = useState(false) + const [error, setError] = useState(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 ( +
+
+

Nyckeltal

+

Γ–versikt av fΓΆretagets ekonomiska hΓ€lsa

+
+ +
+ ) + } + + return ( +
+
+
+

Nyckeltal

+

Γ–versikt av fΓΆretagets ekonomiska hΓ€lsa

+
+
+ + {/* Period selector */} + {periods.length > 0 && ( +
+ + +
+ )} + + {error && ( + + +

{error}

+
+
+ )} + + {isLoadingReport && } + + {!isLoadingReport && !error && report && ( + <> + + + {report.months.length > 0 && } + + )} + + {!isLoadingReport && !error && !report && periods.length === 0 && ( + + +

Inget rΓ€kenskapsΓ₯r hittades. Skapa ett rΓ€kenskapsΓ₯r fΓΆr att se nyckeltal.

+
+
+ )} +
+ ) +} + +function LoadingSkeleton() { + return ( +
+
+ {[1, 2, 3, 4].map((i) => ( + + +
+
+
+ + + ))} +
+
+ {[1, 2, 3, 4].map((i) => ( + + +
+
+ + + ))} +
+ + +
+
+ + +
+ ) +} diff --git a/app/(dashboard)/settings/page.tsx b/app/(dashboard)/settings/page.tsx index 23dbed2d..15878845 100644 --- a/app/(dashboard)/settings/page.tsx +++ b/app/(dashboard)/settings/page.tsx @@ -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(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(null) const [bankgiroError, setBankgiroError] = useState(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() { + {/* API keys */} + {hasMcpExtension && ( + + + + )} + {/* Account settings */} diff --git a/app/.well-known/oauth-authorization-server/route.ts b/app/.well-known/oauth-authorization-server/route.ts new file mode 100644 index 00000000..f1397d79 --- /dev/null +++ b/app/.well-known/oauth-authorization-server/route.ts @@ -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'], + }) +} diff --git a/app/.well-known/oauth-protected-resource/route.ts b/app/.well-known/oauth-protected-resource/route.ts new file mode 100644 index 00000000..cc52cc96 --- /dev/null +++ b/app/.well-known/oauth-protected-resource/route.ts @@ -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'], + }) +} diff --git a/app/api/mcp-oauth/authorize/route.ts b/app/api/mcp-oauth/authorize/route.ts new file mode 100644 index 00000000..d450f372 --- /dev/null +++ b/app/api/mcp-oauth/authorize/route.ts @@ -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 = ` + + + + + + Anslut MCP-klient β€” gnubok + + + +
+

Anslut MCP-klient

+

En extern applikation vill ansluta till ditt gnubok-konto.

+ +
    +
  • Visa och kategorisera transaktioner
  • +
  • Skapa och visa fakturor
  • +
  • Visa kunder och rapporter
  • +
  • Skapa verifikationer
  • +
+
+
+ + +
+
+ + +
+
+
+ +` + + 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, '"') +} diff --git a/app/api/mcp-oauth/register/route.ts b/app/api/mcp-oauth/register/route.ts new file mode 100644 index 00000000..f24a5231 --- /dev/null +++ b/app/api/mcp-oauth/register/route.ts @@ -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 + 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 }) +} diff --git a/app/api/mcp-oauth/token/route.ts b/app/api/mcp-oauth/token/route.ts new file mode 100644 index 00000000..ca875b64 --- /dev/null +++ b/app/api/mcp-oauth/token/route.ts @@ -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) + } 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', + }) +} diff --git a/app/api/reports/kpi/route.ts b/app/api/reports/kpi/route.ts new file mode 100644 index 00000000..9dca8237 --- /dev/null +++ b/app/api/reports/kpi/route.ts @@ -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 }) +} diff --git a/app/api/settings/api-keys/[id]/route.ts b/app/api/settings/api-keys/[id]/route.ts new file mode 100644 index 00000000..9caa5ec7 --- /dev/null +++ b/app/api/settings/api-keys/[id]/route.ts @@ -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 }) +} diff --git a/app/api/settings/api-keys/route.ts b/app/api/settings/api-keys/route.ts new file mode 100644 index 00000000..5d73f8a4 --- /dev/null +++ b/app/api/settings/api-keys/route.ts @@ -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 + }, + }) +} diff --git a/components/dashboard/DashboardNav.tsx b/components/dashboard/DashboardNav.tsx index 3adee348..fafad8c3 100644 --- a/components/dashboard/DashboardNav.tsx +++ b/components/dashboard/DashboardNav.tsx @@ -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' }, diff --git a/components/kpi/KPIHeroCards.tsx b/components/kpi/KPIHeroCards.tsx new file mode 100644 index 00000000..05912ee8 --- /dev/null +++ b/components/kpi/KPIHeroCards.tsx @@ -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 ( +
+ {/* Gross margin */} + + +

Bruttomarginal

+

+ {report.grossMargin !== null ? `${report.grossMargin}%` : 'β€”'} +

+

av intΓ€kter

+
+
+ + {/* Net result */} + + +

Resultat

+

= 0 ? 'text-[hsl(var(--chart-1))]' : 'text-[hsl(var(--chart-2))]' + }`}> + {formatCurrency(report.netResult)} +

+

netto

+
+
+ + {/* Cash position */} + + +

Kassa

+

0 ? 'text-[hsl(var(--chart-1))]' : 'text-[hsl(var(--chart-2))]' + }`}> + {formatCurrency(report.cashPosition)} +

+

likvida medel

+
+
+ + {/* Outstanding receivables */} + + +

Kundfordringar

+

+ {formatCurrency(report.outstandingReceivables)} +

+ {report.overdueReceivables > 0 ? ( +

+ varav fΓΆrfallet: {formatCurrency(report.overdueReceivables)} +

+ ) : ( +

utestΓ₯ende

+ )} +
+
+
+ ) +} diff --git a/components/kpi/KPIOperationalGrid.tsx b/components/kpi/KPIOperationalGrid.tsx new file mode 100644 index 00000000..5e95e109 --- /dev/null +++ b/components/kpi/KPIOperationalGrid.tsx @@ -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 ( +
+ {/* Revenue growth */} + + +

IntΓ€ktstillvΓ€xt

+ {!report.periodComplete ? ( +

VΓ€lj ett avslutat rΓ€kenskapsΓ₯r

+ ) : report.revenueGrowth !== null ? ( +
+ {report.revenueGrowth >= 0 ? ( + + ) : ( + + )} +

= 0 ? 'text-[hsl(var(--chart-1))]' : 'text-[hsl(var(--chart-2))]' + }`}> + {report.revenueGrowth > 0 ? '+' : ''}{report.revenueGrowth}% +

+
+ ) : ( +

FΓΆrsta rΓ€kenskapsΓ₯ret

+ )} +
+
+ + {/* Expense ratio */} + + +

Kostnadsandel

+ {report.expenseRatio !== null ? ( + <> +

+ {report.expenseRatio}% +

+
+
+
+ + ) : ( +

Inga intΓ€kter

+ )} + + + + {/* Avg payment days */} + + +
+

Snittbetaltid

+ {report.avgPaymentDays === null && ( + + + + )} +
+ {report.avgPaymentDays !== null ? ( +

+ {report.avgPaymentDays} dagar +

+ ) : ( +

Inte tillrΓ€ckligt med data

+ )} +
+
+ + {/* VAT liability */} + + +

Momsskuld

+

0 ? 'text-[hsl(var(--chart-2))]' : 'text-[hsl(var(--chart-1))]' + }`}> + {formatCurrency(Math.abs(report.vatLiability))} +

+

+ {report.vatLiability > 0 ? 'Att betala' : report.vatLiability < 0 ? 'Att Γ₯terfΓ₯' : 'JΓ€mnt'} +

+
+
+
+ ) +} diff --git a/components/kpi/KPITrendChart.tsx b/components/kpi/KPITrendChart.tsx new file mode 100644 index 00000000..359755c1 --- /dev/null +++ b/components/kpi/KPITrendChart.tsx @@ -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 ( + + + IntΓ€kter, kostnader & resultat per mΓ₯nad + + + + + + + + new Intl.NumberFormat('sv-SE', { notation: 'compact' }).format(v) + } + tick={{ fontSize: 11 }} + /> + [ + 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))', + }} + /> + + value === 'income' + ? 'IntΓ€kter' + : value === 'expenses' + ? 'Kostnader' + : 'Resultat' + } + /> + + + + + + + + ) +} diff --git a/components/settings/ApiKeysPanel.tsx b/components/settings/ApiKeysPanel.tsx new file mode 100644 index 00000000..3052f1a7 --- /dev/null +++ b/components/settings/ApiKeysPanel.tsx @@ -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([]) + 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(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 ( +
+ + +
+
+ API-nycklar + + Hantera nycklar fΓΆr MCP-klienter (Claude, Cursor) och andra integrationer. + +
+ +
+
+ + {isLoading ? ( +
+ +
+ ) : keys.length === 0 ? ( +
+ +

Inga API-nycklar Γ€nnu.

+

+ Skapa en nyckel fΓΆr att koppla din MCP-klient. +

+
+ ) : ( +
+ {keys.map((key) => ( +
+
+
+

{key.name}

+
+
+ + {key.key_prefix}... + + + Skapad {formatDate(key.created_at)} + + + {key.last_used_at + ? `AnvΓ€nd ${formatDate(key.last_used_at)}` + : 'Aldrig anvΓ€nd'} + +
+
+ +
+ ))} +
+ )} +
+
+ + + + Anslut MCP-klient + + +
+

Claude Desktop

+

+ InstΓ€llningar → Connectors → Add custom connector. Klistra in URL:en nedan. + Du loggas in automatiskt via OAuth. +

+
+{mcpUrl}
+            
+
+ +
+

Claude Code / Cursor

+

+ KΓΆr i terminalen med en API-nyckel: +

+
+{`claude mcp add gnubok --transport http \\
+  --url ${mcpUrl} \\
+  --header "Authorization: Bearer gnubok_sk_..."`}
+            
+
+
+
+ + {/* Create key dialog */} + + + + Skapa API-nyckel + + Ge nyckeln ett namn sΓ₯ du vet vad den anvΓ€nds till. + + +
+ + setNewKeyName(e.target.value)} + onKeyDown={(e) => e.key === 'Enter' && handleCreate()} + /> +
+ + + + +
+
+ + {/* Show key once dialog */} + { + if (!open) { + setNewKeyValue('') + setCopied(false) + } + setShowKeyDialog(open) + }}> + + + Din nya API-nyckel + + Kopiera nyckeln nu. Den visas bara en gΓ₯ng. + + +
+ + {newKeyValue} + + +
+ + + +
+
+
+ ) +} diff --git a/extensions.config.json b/extensions.config.json index 10fd7ecd..034615ea 100644 --- a/extensions.config.json +++ b/extensions.config.json @@ -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"]} diff --git a/extensions.schema.json b/extensions.schema.json index d069bf30..a5d767e0 100644 --- a/extensions.schema.json +++ b/extensions.schema.json @@ -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." diff --git a/extensions/general/mcp-server/index.ts b/extensions/general/mcp-server/index.ts new file mode 100644 index 00000000..ad213a4d --- /dev/null +++ b/extensions/general/mcp-server/index.ts @@ -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: [], +} diff --git a/extensions/general/mcp-server/manifest.json b/extensions/general/mcp-server/manifest.json new file mode 100644 index 00000000..1f1fb125 --- /dev/null +++ b/extensions/general/mcp-server/manifest.json @@ -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." + } +} diff --git a/extensions/general/mcp-server/server.ts b/extensions/general/mcp-server/server.ts new file mode 100644 index 00000000..af7dd7fd --- /dev/null +++ b/extensions/general/mcp-server/server.ts @@ -0,0 +1,1347 @@ +import { NextResponse } from 'next/server' +import { + extractBearerToken, + validateApiKey, + createServiceClientNoCookies, +} from '@/lib/auth/api-keys' +import type { SupabaseClient } from '@supabase/supabase-js' +import { buildMappingResultFromCategory } from '@/lib/bookkeeping/category-mapping' +import { createTransactionJournalEntry } from '@/lib/bookkeeping/transaction-entries' +import { eventBus } from '@/lib/events/bus' +import { getVatRules, getAvailableVatRates } from '@/lib/invoices/vat-rules' +import { fetchExchangeRate, convertToSEK } from '@/lib/currency/riksbanken' +import { generateIncomeStatement } from '@/lib/reports/income-statement' +import { + calculateGrossMargin, + calculateCashPosition, + calculateExpenseRatio, + calculateAvgPaymentDays, +} from '@/lib/reports/kpi' +import { generateTrialBalance } from '@/lib/reports/trial-balance' +import { generateARLedger } from '@/lib/reports/ar-ledger' +import { generateMonthlyBreakdown } from '@/lib/reports/monthly-breakdown' +// ensureInitialized() is called by the extension router (ext/[...path]/route.ts) +// which dispatches to this handler β€” no duplicate call needed here. +import type { Transaction, TransactionCategory, EntityType, VatTreatment, Invoice, Currency } from '@/types' + +// ── JSON-RPC types ─────────────────────────────────────────── + +interface JsonRpcRequest { + jsonrpc: '2.0' + id?: string | number + method: string + params?: Record +} + +interface JsonRpcResponse { + jsonrpc: '2.0' + id: string | number | null + result?: unknown + error?: { code: number; message: string; data?: unknown } +} + +// ── MCP Tool definition ────────────────────────────────────── + +interface McpToolAnnotations { + readOnlyHint?: boolean + destructiveHint?: boolean + idempotentHint?: boolean + openWorldHint?: boolean +} + +interface McpTool { + name: string + description: string + inputSchema: Record + annotations: McpToolAnnotations + execute: ( + args: Record, + userId: string, + supabase: SupabaseClient + ) => Promise +} + +// ── Shared constants ───────────────────────────────────────── + +const VALID_CATEGORIES = [ + 'income_services', 'income_products', 'income_other', + 'expense_equipment', 'expense_software', 'expense_travel', 'expense_office', + 'expense_marketing', 'expense_professional_services', 'expense_education', + 'expense_representation', 'expense_consumables', 'expense_vehicle', + 'expense_telecom', 'expense_bank_fees', 'expense_card_fees', + 'expense_currency_exchange', 'expense_other', 'private', +] as const + +const VALID_VAT_TREATMENTS = [ + 'standard_25', 'reduced_12', 'reduced_6', 'reverse_charge', 'export', 'exempt', +] as const + +// ── Tools ──────────────────────────────────────────────────── + +const tools: McpTool[] = [ + { + name: 'gnubok_list_uncategorized_transactions', + description: + 'List bank transactions that have not been categorized (no journal entry yet). ' + + 'Use this to see what needs bookkeeping attention.\n\n' + + 'Args:\n' + + ' - limit (number, optional): Max results, 1–100 (default: 20)\n' + + ' - offset (number, optional): Skip first N results for pagination (default: 0)\n\n' + + 'Returns JSON:\n' + + ' { transactions: [{ id, date, description, amount, currency, merchant_name, reference }],\n' + + ' count: number, total_count: number, has_more: boolean, next_offset?: number }\n\n' + + 'Examples:\n' + + ' - "Show my uncategorized transactions" β†’ call with no args\n' + + ' - "Show next 50" β†’ call with limit=50\n' + + ' - "Show page 2" β†’ call with offset=20\n\n' + + 'Error: Returns error text if the database query fails.', + inputSchema: { + type: 'object', + properties: { + limit: { + type: 'number', + description: 'Max results to return, 1–100 (default 20)', + }, + offset: { + type: 'number', + description: 'Number of results to skip for pagination (default 0)', + }, + }, + }, + annotations: { + readOnlyHint: true, + destructiveHint: false, + idempotentHint: true, + openWorldHint: false, + }, + async execute(args, userId, supabase) { + const limit = Math.min(Math.max(1, Number(args.limit) || 20), 100) + const offset = Math.max(0, Number(args.offset) || 0) + + // Get total count + const { count: totalCount, error: countError } = await supabase + .from('transactions') + .select('id', { count: 'exact', head: true }) + .eq('user_id', userId) + .is('journal_entry_id', null) + + if (countError) throw new Error(`Database error: ${countError.message}`) + + const { data, error } = await supabase + .from('transactions') + .select( + 'id, date, description, amount, currency, merchant_name, reference, is_business, category' + ) + .eq('user_id', userId) + .is('journal_entry_id', null) + .order('date', { ascending: false }) + .range(offset, offset + limit - 1) + + if (error) throw new Error(`Database error: ${error.message}`) + + const total = totalCount ?? 0 + const hasMore = total > offset + (data?.length ?? 0) + + return { + transactions: data, + count: data?.length ?? 0, + total_count: total, + has_more: hasMore, + ...(hasMore ? { next_offset: offset + (data?.length ?? 0) } : {}), + } + }, + }, + + { + name: 'gnubok_categorize_transaction', + description: + 'Categorize a bank transaction and create the corresponding double-entry journal entry. ' + + 'This books the transaction in the accounting ledger using Swedish BAS accounts.\n\n' + + 'Args:\n' + + ' - transaction_id (string, required): UUID of the transaction from gnubok_list_uncategorized_transactions\n' + + ' - category (string, required): One of: ' + VALID_CATEGORIES.join(', ') + '\n' + + ' - vat_treatment (string, optional): One of: ' + VALID_VAT_TREATMENTS.join(', ') + '. ' + + 'Defaults to standard_25 for business expenses.\n\n' + + 'Returns JSON:\n' + + ' { success: boolean, journal_entry_created: boolean, journal_entry_id?: string,\n' + + ' category: string, debit_account: string, credit_account: string }\n\n' + + 'Examples:\n' + + ' - "Book that as office supplies, 25% VAT" β†’ category="expense_office"\n' + + ' - "Mark as private" β†’ category="private" (no journal entry created for private)\n' + + ' - "Book as consulting income" β†’ category="income_services"\n\n' + + 'Errors:\n' + + ' - "Transaction not found" if the ID is invalid or belongs to another user\n' + + ' - "Transaction already has a journal entry" if already categorized\n' + + ' - "Invalid account mapping" if the category/entity type combination has no mapping', + inputSchema: { + type: 'object', + properties: { + transaction_id: { + type: 'string', + description: 'UUID of the transaction to categorize', + }, + category: { + type: 'string', + description: 'Transaction category', + enum: [...VALID_CATEGORIES], + }, + vat_treatment: { + type: 'string', + description: 'VAT treatment override', + enum: [...VALID_VAT_TREATMENTS], + }, + }, + required: ['transaction_id', 'category'], + }, + annotations: { + readOnlyHint: false, + destructiveHint: false, + idempotentHint: false, + openWorldHint: false, + }, + async execute(args, userId, supabase) { + const txId = args.transaction_id as string + const category = args.category as TransactionCategory + const vatTreatment = args.vat_treatment as VatTreatment | undefined + + // Validate category + if (!VALID_CATEGORIES.includes(category as typeof VALID_CATEGORIES[number])) { + throw new Error( + `Invalid category "${category}". Valid categories: ${VALID_CATEGORIES.join(', ')}` + ) + } + + if (vatTreatment && !VALID_VAT_TREATMENTS.includes(vatTreatment as typeof VALID_VAT_TREATMENTS[number])) { + throw new Error( + `Invalid vat_treatment "${vatTreatment}". Valid: ${VALID_VAT_TREATMENTS.join(', ')}` + ) + } + + const isBusiness = category !== 'private' + + // Fetch the transaction + const { data: transaction, error: fetchError } = await supabase + .from('transactions') + .select('*') + .eq('id', txId) + .eq('user_id', userId) + .single() + + if (fetchError || !transaction) { + throw new Error('Transaction not found. Check the transaction_id is correct.') + } + + if (transaction.journal_entry_id) { + return { + success: true, + journal_entry_created: false, + message: 'Transaction already has a journal entry β€” use gnubok_list_uncategorized_transactions to find unboooked ones.', + journal_entry_id: transaction.journal_entry_id, + } + } + + // Get entity type + const { data: settings } = await supabase + .from('company_settings') + .select('entity_type, fiscal_year_start_month') + .eq('user_id', userId) + .single() + + const entityType: EntityType = (settings?.entity_type as EntityType) || 'enskild_firma' + + // Build mapping + const mappingResult = buildMappingResultFromCategory( + category, + transaction as Transaction, + isBusiness, + entityType, + vatTreatment + ) + + if (!mappingResult.debit_account || !mappingResult.credit_account) { + throw new Error( + `No account mapping for category "${category}" with entity type "${entityType}". ` + + 'Try a different category or check your chart of accounts.' + ) + } + + // Ensure fiscal period exists + const fiscalYearStartMonth = settings?.fiscal_year_start_month ?? 1 + const txDate = new Date(transaction.date) + const txMonth = txDate.getMonth() + 1 + const txYear = txDate.getFullYear() + + let periodStartYear: number + if (fiscalYearStartMonth === 1) { + periodStartYear = txYear + } else if (txMonth >= fiscalYearStartMonth) { + periodStartYear = txYear + } else { + periodStartYear = txYear - 1 + } + + const startMonth = String(fiscalYearStartMonth).padStart(2, '0') + const periodStart = `${periodStartYear}-${startMonth}-01` + + const endYear = fiscalYearStartMonth === 1 ? periodStartYear : periodStartYear + 1 + const endMonth = fiscalYearStartMonth === 1 ? 12 : fiscalYearStartMonth - 1 + const lastDay = new Date(endYear, endMonth, 0).getDate() + const periodEnd = `${endYear}-${String(endMonth).padStart(2, '0')}-${String(lastDay).padStart(2, '0')}` + + const periodName = fiscalYearStartMonth === 1 + ? `RΓ€kenskapsΓ₯r ${periodStartYear}` + : `RΓ€kenskapsΓ₯r ${periodStartYear}/${endYear}` + + await supabase + .from('fiscal_periods') + .upsert( + { user_id: userId, name: periodName, period_start: periodStart, period_end: periodEnd }, + { onConflict: 'user_id,period_start,period_end' } + ) + + // Create journal entry + let journalEntryId: string | null = null + let journalEntryError: string | null = null + + try { + const journalEntry = await createTransactionJournalEntry( + supabase, + userId, + transaction as Transaction, + mappingResult + ) + if (journalEntry) { + journalEntryId = journalEntry.id + } + } catch (err) { + journalEntryError = err instanceof Error ? err.message : 'Unknown error' + } + + // Update transaction + await supabase + .from('transactions') + .update({ + is_business: isBusiness, + category, + journal_entry_id: journalEntryId, + }) + .eq('id', txId) + + // Emit event so extensions (mapping rules, etc.) can react + await eventBus.emit({ + type: 'transaction.categorized', + payload: { + transaction: transaction as Transaction, + account: mappingResult.debit_account, + taxCode: mappingResult.vat_lines[0]?.account_number || '', + userId, + }, + }) + + return { + success: true, + journal_entry_created: !!journalEntryId, + journal_entry_id: journalEntryId, + journal_entry_error: journalEntryError, + category, + debit_account: mappingResult.debit_account, + credit_account: mappingResult.credit_account, + amount: Math.abs(transaction.amount), + currency: transaction.currency, + } + }, + }, + + // ── Customer tools ─────────────────────────────────────────── + + { + name: 'gnubok_list_customers', + description: + 'List all customers. Use this to look up customer IDs for invoice creation.\n\n' + + 'Args: none\n\n' + + 'Returns JSON:\n' + + ' { customers: [{ id, name, customer_type, email, org_number, vat_number, default_payment_terms }],\n' + + ' count: number }', + inputSchema: { type: 'object', properties: {} }, + annotations: { + readOnlyHint: true, + destructiveHint: false, + idempotentHint: true, + openWorldHint: false, + }, + async execute(_args, userId, supabase) { + const { data, error } = await supabase + .from('customers') + .select('id, name, customer_type, email, org_number, vat_number, default_payment_terms, city, country') + .eq('user_id', userId) + .order('name') + + if (error) throw new Error(`Database error: ${error.message}`) + + return { customers: data, count: data?.length ?? 0 } + }, + }, + + { + name: 'gnubok_create_customer', + description: + 'Create a new customer. Required for invoice creation.\n\n' + + 'Args:\n' + + ' - name (string, required): Customer/company name\n' + + ' - customer_type (string, required): individual, swedish_business, eu_business, non_eu_business\n' + + ' - email (string, optional): Contact email\n' + + ' - org_number (string, optional): Swedish org number (for swedish_business)\n' + + ' - vat_number (string, optional): EU VAT number (for eu_business, triggers VIES validation)\n' + + ' - payment_terms (number, optional): Days until due (default 30)\n' + + ' - address (string, optional): Street address\n' + + ' - postal_code (string, optional)\n' + + ' - city (string, optional)\n' + + ' - country (string, optional): Defaults to Sweden\n\n' + + 'Returns JSON: the created customer object with id.\n\n' + + 'Examples:\n' + + ' - "Add Acme AB" β†’ name="Acme AB", customer_type="swedish_business"\n' + + ' - "Add a German client" β†’ customer_type="eu_business", country="Germany"', + inputSchema: { + type: 'object', + properties: { + name: { type: 'string', description: 'Customer name' }, + customer_type: { + type: 'string', + enum: ['individual', 'swedish_business', 'eu_business', 'non_eu_business'], + description: 'Customer type', + }, + email: { type: 'string', description: 'Email address' }, + org_number: { type: 'string', description: 'Swedish org number' }, + vat_number: { type: 'string', description: 'EU VAT number' }, + payment_terms: { type: 'number', description: 'Payment terms in days (default 30)' }, + address: { type: 'string', description: 'Street address' }, + postal_code: { type: 'string' }, + city: { type: 'string' }, + country: { type: 'string', description: 'Country (default Sweden)' }, + }, + required: ['name', 'customer_type'], + }, + annotations: { + readOnlyHint: false, + destructiveHint: false, + idempotentHint: false, + openWorldHint: false, + }, + async execute(args, userId, supabase) { + const name = args.name as string + const customerType = args.customer_type as string + + if (!name?.trim()) throw new Error('Customer name is required.') + if (!['individual', 'swedish_business', 'eu_business', 'non_eu_business'].includes(customerType)) { + throw new Error('Invalid customer_type. Must be: individual, swedish_business, eu_business, non_eu_business') + } + + const { data, error } = await supabase + .from('customers') + .insert({ + user_id: userId, + name: name.trim(), + customer_type: customerType, + email: (args.email as string) || null, + org_number: (args.org_number as string) || null, + vat_number: (args.vat_number as string) || null, + default_payment_terms: Number(args.payment_terms) || 30, + address_line1: (args.address as string) || null, + postal_code: (args.postal_code as string) || null, + city: (args.city as string) || null, + country: (args.country as string) || 'Sweden', + }) + .select() + .single() + + if (error) throw new Error(`Failed to create customer: ${error.message}`) + + return { customer: data } + }, + }, + + // ── Invoice tools ──────────────────────────────────────────── + + { + name: 'gnubok_list_invoices', + description: + 'List invoices, optionally filtered by status.\n\n' + + 'Args:\n' + + ' - status (string, optional): Filter by status: draft, sent, paid, overdue, cancelled, credited\n' + + ' - limit (number, optional): Max results, 1–100 (default 50)\n\n' + + 'Returns JSON:\n' + + ' { invoices: [{ id, invoice_number, status, customer_name, total, currency, invoice_date, due_date }],\n' + + ' count: number, total_count: number }\n\n' + + 'Examples:\n' + + ' - "Show unpaid invoices" β†’ status="sent"\n' + + ' - "Show overdue invoices" β†’ status="overdue"', + inputSchema: { + type: 'object', + properties: { + status: { + type: 'string', + enum: ['draft', 'sent', 'paid', 'overdue', 'cancelled', 'credited'], + description: 'Filter by invoice status', + }, + limit: { type: 'number', description: 'Max results (default 50, max 100)' }, + }, + }, + annotations: { + readOnlyHint: true, + destructiveHint: false, + idempotentHint: true, + openWorldHint: false, + }, + async execute(args, userId, supabase) { + const limit = Math.min(Math.max(1, Number(args.limit) || 50), 100) + const status = args.status as string | undefined + + let query = supabase + .from('invoices') + .select('id, invoice_number, status, customer_id, total, currency, invoice_date, due_date, document_type, customers(name)', { count: 'exact' }) + .eq('user_id', userId) + + if (status) { + query = query.eq('status', status) + } + + const { data, error, count } = await query + .order('invoice_date', { ascending: false }) + .limit(limit) + + if (error) throw new Error(`Database error: ${error.message}`) + + const invoices = (data ?? []).map((inv: Record) => ({ + id: inv.id, + invoice_number: inv.invoice_number, + status: inv.status, + customer_name: (inv.customers as Record)?.name ?? null, + total: inv.total, + currency: inv.currency, + invoice_date: inv.invoice_date, + due_date: inv.due_date, + document_type: inv.document_type, + })) + + return { + invoices, + count: invoices.length, + total_count: count ?? invoices.length, + } + }, + }, + + { + name: 'gnubok_create_invoice', + description: + 'Create a new invoice for a customer. Automatically calculates VAT based on customer type.\n\n' + + 'Args:\n' + + ' - customer_id (string, required): UUID from gnubok_list_customers\n' + + ' - items (array, required): Line items, each with:\n' + + ' - description (string): What was sold/delivered\n' + + ' - quantity (number): How many\n' + + ' - unit (string): Unit of measure (st, tim, dag, mΓ₯n)\n' + + ' - unit_price (number): Price per unit excl. VAT\n' + + ' - vat_rate (number, optional): Override VAT rate (0–100)\n' + + ' - invoice_date (string, optional): YYYY-MM-DD (default today)\n' + + ' - due_date (string, optional): YYYY-MM-DD (default based on payment terms)\n' + + ' - currency (string, optional): SEK, EUR, USD, GBP, NOK, DKK (default SEK)\n' + + ' - our_reference (string, optional)\n' + + ' - your_reference (string, optional)\n' + + ' - notes (string, optional): Notes printed on invoice\n\n' + + 'Returns JSON: the created invoice with id, invoice_number, total, vat_amount.\n\n' + + 'Examples:\n' + + ' - "Invoice Acme for 15000 kr consulting" β†’ items=[{description:"KonsulttjΓ€nster",quantity:1,unit:"st",unit_price:15000}]\n' + + ' - "Invoice 10 hours at 1500/h" β†’ items=[{description:"KonsulttjΓ€nster",quantity:10,unit:"tim",unit_price:1500}]', + inputSchema: { + type: 'object', + properties: { + customer_id: { type: 'string', description: 'Customer UUID' }, + items: { + type: 'array', + items: { + type: 'object', + properties: { + description: { type: 'string' }, + quantity: { type: 'number' }, + unit: { type: 'string', description: 'st, tim, dag, mΓ₯n' }, + unit_price: { type: 'number', description: 'Price per unit excl. VAT' }, + vat_rate: { type: 'number', description: 'VAT rate 0–100 (optional override)' }, + }, + required: ['description', 'quantity', 'unit', 'unit_price'], + }, + description: 'Invoice line items', + }, + invoice_date: { type: 'string', description: 'YYYY-MM-DD (default today)' }, + due_date: { type: 'string', description: 'YYYY-MM-DD (default from payment terms)' }, + currency: { type: 'string', enum: ['SEK', 'EUR', 'USD', 'GBP', 'NOK', 'DKK'] }, + our_reference: { type: 'string' }, + your_reference: { type: 'string' }, + notes: { type: 'string' }, + }, + required: ['customer_id', 'items'], + }, + annotations: { + readOnlyHint: false, + destructiveHint: false, + idempotentHint: false, + openWorldHint: false, + }, + async execute(args, userId, supabase) { + const customerId = args.customer_id as string + const items = args.items as Array<{ + description: string + quantity: number + unit: string + unit_price: number + vat_rate?: number + }> + + if (!customerId) throw new Error('customer_id is required. Use gnubok_list_customers to find IDs.') + if (!items?.length) throw new Error('At least one item is required.') + + for (const [i, item] of items.entries()) { + if (!item.description?.trim()) throw new Error(`Item ${i + 1}: description is required`) + if (!item.quantity || item.quantity <= 0) throw new Error(`Item ${i + 1}: quantity must be positive`) + if (!item.unit?.trim()) throw new Error(`Item ${i + 1}: unit is required (st, tim, dag)`) + if (item.unit_price == null) throw new Error(`Item ${i + 1}: unit_price is required`) + } + + const today = new Date().toISOString().split('T')[0] + const currency = ((args.currency as string) || 'SEK') as Currency + const invoiceDate = (args.invoice_date as string) || today + + // Fetch customer (full row for VAT rules) + const { data: customer, error: custError } = await supabase + .from('customers') + .select('*') + .eq('id', customerId) + .eq('user_id', userId) + .single() + + if (custError || !customer) { + throw new Error('Customer not found. Use gnubok_list_customers to find valid IDs.') + } + + // VAT rules from customer type (same logic as web UI) + const vatRules = getVatRules(customer.customer_type, customer.vat_number_validated) + const availableRates = getAvailableVatRates(customer.customer_type, customer.vat_number_validated) + const allowedRates = new Set(availableRates.map((r) => r.rate)) + + // Calculate per-item VAT + const subtotal = items.reduce((s, item) => s + item.quantity * item.unit_price, 0) + let vatAmount = 0 + for (const item of items) { + const itemRate = item.vat_rate !== undefined ? item.vat_rate : vatRules.rate + if (!allowedRates.has(itemRate)) { + throw new Error( + `VAT rate ${itemRate}% is not allowed for customer type "${customer.customer_type}". ` + + `Allowed rates: ${availableRates.map((r) => r.rate + '%').join(', ')}` + ) + } + const lineTotal = item.quantity * item.unit_price + vatAmount += Math.round(lineTotal * itemRate / 100 * 100) / 100 + } + const total = subtotal + vatAmount + + // Mixed-rate detection + const uniqueRates = new Set(items.map((item) => item.vat_rate ?? vatRules.rate)) + + // Currency exchange (Riksbanken) + let exchangeRate: number | null = null + let exchangeRateDate: string | null = null + let subtotalSek: number | null = null + let vatAmountSek: number | null = null + let totalSek: number | null = null + + if (currency !== 'SEK') { + const rateData = await fetchExchangeRate(currency) + if (rateData) { + exchangeRate = rateData.rate + exchangeRateDate = rateData.date + subtotalSek = convertToSEK(subtotal, exchangeRate) + vatAmountSek = convertToSEK(vatAmount, exchangeRate) + totalSek = convertToSEK(total, exchangeRate) + } + } + + // Due date from payment terms if not provided + let dueDate = args.due_date as string | undefined + if (!dueDate) { + const d = new Date(invoiceDate) + d.setDate(d.getDate() + (customer.default_payment_terms || 30)) + dueDate = d.toISOString().split('T')[0] + } + + // Generate invoice number via DB RPC (sequential, same as web UI) + const { data: baseNumber } = await supabase.rpc('generate_invoice_number', { + p_user_id: userId, + }) + const invoiceNumber = baseNumber as string + + // Create invoice + const { data: invoice, error: insertError } = await supabase + .from('invoices') + .insert({ + user_id: userId, + customer_id: customerId, + invoice_number: invoiceNumber, + invoice_date: invoiceDate, + due_date: dueDate, + status: 'draft', + currency, + exchange_rate: exchangeRate, + exchange_rate_date: exchangeRateDate, + subtotal, + subtotal_sek: subtotalSek, + vat_amount: vatAmount, + vat_amount_sek: vatAmountSek, + total, + total_sek: totalSek, + vat_treatment: vatRules.treatment, + vat_rate: uniqueRates.size > 1 ? null : (uniqueRates.values().next().value ?? vatRules.rate), + moms_ruta: vatRules.momsRuta, + reverse_charge_text: vatRules.reverseChargeText || null, + document_type: 'invoice', + our_reference: (args.our_reference as string) || null, + your_reference: (args.your_reference as string) || null, + notes: (args.notes as string) || null, + }) + .select() + .single() + + if (insertError || !invoice) { + throw new Error(`Failed to create invoice: ${insertError?.message || 'Unknown error'}`) + } + + // Insert items + const invoiceItems = items.map((item, idx) => { + const itemRate = item.vat_rate !== undefined ? item.vat_rate : vatRules.rate + const lineTotal = item.quantity * item.unit_price + const itemVat = Math.round(lineTotal * itemRate / 100 * 100) / 100 + return { + invoice_id: invoice.id, + sort_order: idx, + description: item.description, + quantity: item.quantity, + unit: item.unit, + unit_price: item.unit_price, + line_total: lineTotal, + vat_rate: itemRate, + vat_amount: itemVat, + } + }) + + const { error: itemsError } = await supabase + .from('invoice_items') + .insert(invoiceItems) + + if (itemsError) { + await supabase.from('invoices').delete().eq('id', invoice.id) + throw new Error(`Failed to create invoice items: ${itemsError.message}`) + } + + // Emit event (triggers journal entry creation via event handler) + const { data: completeInvoice } = await supabase + .from('invoices') + .select('*, customer:customers(*), items:invoice_items(*)') + .eq('id', invoice.id) + .single() + + if (completeInvoice) { + await eventBus.emit({ + type: 'invoice.created', + payload: { invoice: completeInvoice as Invoice, userId }, + }) + } + + return { + invoice: { + id: invoice.id, + invoice_number: invoiceNumber, + status: 'draft', + customer_name: customer.name, + subtotal: Math.round(subtotal * 100) / 100, + vat_amount: Math.round(vatAmount * 100) / 100, + total: Math.round(total * 100) / 100, + currency, + vat_treatment: vatRules.treatment, + invoice_date: invoiceDate, + due_date: dueDate, + item_count: invoiceItems.length, + ...(exchangeRate ? { exchange_rate: exchangeRate, total_sek: totalSek } : {}), + }, + note: 'Invoice created as draft. Use the web UI to send it.', + } + }, + }, + + // ── Report tools ───────────────────────────────────────────── + + { + name: 'gnubok_get_trial_balance', + description: + 'Get the trial balance (huvudbok) for a fiscal period. Shows all account balances.\n\n' + + 'Args:\n' + + ' - period_id (string, optional): Fiscal period UUID. If omitted, uses the most recent period.\n\n' + + 'Returns JSON:\n' + + ' { rows: [{ account_number, account_name, period_debit, period_credit, closing_debit, closing_credit }],\n' + + ' total_debit: number, total_credit: number, is_balanced: boolean, period_name: string }\n\n' + + 'Examples:\n' + + ' - "What are my account balances?" β†’ call with no args\n' + + ' - "Trial balance for last year" β†’ provide the period_id', + inputSchema: { + type: 'object', + properties: { + period_id: { type: 'string', description: 'Fiscal period UUID (default: most recent)' }, + }, + }, + annotations: { + readOnlyHint: true, + destructiveHint: false, + idempotentHint: true, + openWorldHint: false, + }, + async execute(args, userId, supabase) { + let periodId = args.period_id as string | undefined + + // If no period specified, find the most recent one + if (!periodId) { + const { data: periods } = await supabase + .from('fiscal_periods') + .select('id, name') + .eq('user_id', userId) + .order('period_start', { ascending: false }) + .limit(1) + .single() + + if (!periods) { + throw new Error('No fiscal periods found. Categorize some transactions first to auto-create a period.') + } + periodId = periods.id + } + + // Get period info + const { data: period } = await supabase + .from('fiscal_periods') + .select('id, name, period_start, period_end') + .eq('id', periodId) + .eq('user_id', userId) + .single() + + if (!period) throw new Error('Fiscal period not found.') + + // Aggregate journal entry lines + const { data: lines, error } = await supabase + .from('journal_entry_lines') + .select('account_number, debit_amount, credit_amount, journal_entries!inner(status, user_id, fiscal_period_id)') + .eq('journal_entries.user_id', userId) + .eq('journal_entries.fiscal_period_id', periodId) + .in('journal_entries.status', ['posted', 'reversed']) + + if (error) throw new Error(`Database error: ${error.message}`) + + // Get account names + const { data: accounts } = await supabase + .from('chart_of_accounts') + .select('account_number, account_name') + .eq('user_id', userId) + + const accountMap = new Map((accounts ?? []).map((a: { account_number: string; account_name: string }) => [a.account_number, a.account_name])) + + // Aggregate by account + const totals = new Map() + for (const line of lines ?? []) { + const acc = line.account_number + const existing = totals.get(acc) ?? { debit: 0, credit: 0 } + existing.debit += Number(line.debit_amount) || 0 + existing.credit += Number(line.credit_amount) || 0 + totals.set(acc, existing) + } + + const rows = Array.from(totals.entries()) + .sort(([a], [b]) => a.localeCompare(b)) + .map(([accNum, t]) => { + const net = Math.round((t.debit - t.credit) * 100) / 100 + return { + account_number: accNum, + account_name: accountMap.get(accNum) ?? accNum, + period_debit: Math.round(t.debit * 100) / 100, + period_credit: Math.round(t.credit * 100) / 100, + closing_debit: net > 0 ? net : 0, + closing_credit: net < 0 ? Math.abs(net) : 0, + } + }) + + const totalDebit = Math.round(rows.reduce((s, r) => s + r.closing_debit, 0) * 100) / 100 + const totalCredit = Math.round(rows.reduce((s, r) => s + r.closing_credit, 0) * 100) / 100 + + return { + rows, + total_debit: totalDebit, + total_credit: totalCredit, + is_balanced: Math.abs(totalDebit - totalCredit) < 0.01, + period_name: period.name, + period_start: period.period_start, + period_end: period.period_end, + account_count: rows.length, + } + }, + }, + + { + name: 'gnubok_get_vat_report', + description: + 'Get the VAT declaration (momsdeklaration) for a period. Shows all rutor (boxes) for SKV 4700.\n\n' + + 'Args:\n' + + ' - period_type (string, required): monthly, quarterly, yearly\n' + + ' - year (number, required): e.g. 2025\n' + + ' - period (number, required): 1–12 for monthly, 1–4 for quarterly, 1 for yearly\n\n' + + 'Returns JSON: VAT declaration with all rutor (05, 10, 11, 12, 48, 49, etc.)\n' + + ' ruta49 = VAT to pay (positive) or refund (negative)\n\n' + + 'Examples:\n' + + ' - "VAT for Q1 2025" β†’ period_type="quarterly", year=2025, period=1\n' + + ' - "VAT for March 2025" β†’ period_type="monthly", year=2025, period=3', + inputSchema: { + type: 'object', + properties: { + period_type: { + type: 'string', + enum: ['monthly', 'quarterly', 'yearly'], + description: 'Period type', + }, + year: { type: 'number', description: 'Year (e.g. 2025)' }, + period: { type: 'number', description: '1–12 for monthly, 1–4 for quarterly, 1 for yearly' }, + }, + required: ['period_type', 'year', 'period'], + }, + annotations: { + readOnlyHint: true, + destructiveHint: false, + idempotentHint: true, + openWorldHint: false, + }, + async execute(args, userId, supabase) { + const periodType = args.period_type as string + const year = Number(args.year) + const period = Number(args.period) + + if (!['monthly', 'quarterly', 'yearly'].includes(periodType)) { + throw new Error('period_type must be: monthly, quarterly, yearly') + } + if (!year || year < 2000 || year > 2100) throw new Error('year must be between 2000 and 2100') + if (periodType === 'monthly' && (period < 1 || period > 12)) throw new Error('period must be 1–12 for monthly') + if (periodType === 'quarterly' && (period < 1 || period > 4)) throw new Error('period must be 1–4 for quarterly') + + // Calculate date range + let startDate: string + let endDate: string + + if (periodType === 'monthly') { + startDate = `${year}-${String(period).padStart(2, '0')}-01` + const lastDay = new Date(year, period, 0).getDate() + endDate = `${year}-${String(period).padStart(2, '0')}-${String(lastDay).padStart(2, '0')}` + } else if (periodType === 'quarterly') { + const startMonth = (period - 1) * 3 + 1 + const endMonth = period * 3 + startDate = `${year}-${String(startMonth).padStart(2, '0')}-01` + const lastDay = new Date(year, endMonth, 0).getDate() + endDate = `${year}-${String(endMonth).padStart(2, '0')}-${String(lastDay).padStart(2, '0')}` + } else { + startDate = `${year}-01-01` + endDate = `${year}-12-31` + } + + // Get all posted journal entry lines in the date range + const { data: lines, error } = await supabase + .from('journal_entry_lines') + .select('account_number, debit_amount, credit_amount, journal_entries!inner(entry_date, status, user_id)') + .eq('journal_entries.user_id', userId) + .in('journal_entries.status', ['posted', 'reversed']) + .gte('journal_entries.entry_date', startDate) + .lte('journal_entries.entry_date', endDate) + + if (error) throw new Error(`Database error: ${error.message}`) + + // Aggregate by account + const accountTotals = new Map() + for (const line of lines ?? []) { + const acc = line.account_number + const existing = accountTotals.get(acc) ?? { debit: 0, credit: 0 } + existing.debit += Number(line.debit_amount) || 0 + existing.credit += Number(line.credit_amount) || 0 + accountTotals.set(acc, existing) + } + + function creditBalance(acc: string): number { + const t = accountTotals.get(acc) + return t ? Math.round((t.credit - t.debit) * 100) / 100 : 0 + } + + function debitBalance(acc: string): number { + const t = accountTotals.get(acc) + return t ? Math.round((t.debit - t.credit) * 100) / 100 : 0 + } + + // Map accounts to rutor + const ruta05 = creditBalance('3001') + creditBalance('3002') + creditBalance('3003') + const ruta10 = creditBalance('2611') + const ruta11 = creditBalance('2621') + const ruta12 = creditBalance('2631') + const ruta39 = creditBalance('3308') + const ruta40 = creditBalance('3305') + const ruta48 = debitBalance('2641') + debitBalance('2645') + const ruta49 = Math.round((ruta10 + ruta11 + ruta12 - ruta48) * 100) / 100 + + const monthNames = ['Januari', 'Februari', 'Mars', 'April', 'Maj', 'Juni', + 'Juli', 'Augusti', 'September', 'Oktober', 'November', 'December'] + + let periodLabel: string + if (periodType === 'monthly') periodLabel = `${monthNames[period - 1]} ${year}` + else if (periodType === 'quarterly') periodLabel = `Q${period} ${year}` + else periodLabel = `${year}` + + return { + period: { type: periodType, year, period, start: startDate, end: endDate }, + period_label: periodLabel, + rutor: { + ruta05: Math.abs(ruta05), + ruta10: Math.abs(ruta10), + ruta11: Math.abs(ruta11), + ruta12: Math.abs(ruta12), + ruta39: Math.abs(ruta39), + ruta40: Math.abs(ruta40), + ruta48: Math.abs(ruta48), + ruta49, + }, + summary: ruta49 > 0 + ? `Moms att betala: ${Math.abs(ruta49).toFixed(2)} kr` + : ruta49 < 0 + ? `Moms att fΓ₯ tillbaka: ${Math.abs(ruta49).toFixed(2)} kr` + : 'Noll i moms', + } + }, + }, + + // ── KPI & Income Statement tools ───────────────────────────── + + { + name: 'gnubok_get_kpi_report', + description: + 'Get key performance indicators for the business. Returns gross margin, net result, cash position, ' + + 'receivables, expense ratio, average payment days, VAT liability, and monthly trend data.\n\n' + + 'Args:\n' + + ' - period_id (string, optional): Fiscal period UUID. If omitted, uses the most recent period.\n\n' + + 'Returns JSON:\n' + + ' { gross_margin: %|null, net_result: SEK, cash_position: SEK, outstanding_receivables: SEK,\n' + + ' overdue_receivables: SEK, expense_ratio: %|null, avg_payment_days: days|null,\n' + + ' vat_liability: SEK, total_revenue: SEK, total_expenses: SEK,\n' + + ' months: [{ label, income, expenses, net }] }\n\n' + + 'Examples:\n' + + ' - "How is my business doing?" β†’ call with no args\n' + + ' - "What are my KPIs?" β†’ call with no args\n' + + ' - "Show me the numbers" β†’ call with no args', + inputSchema: { + type: 'object', + properties: { + period_id: { type: 'string', description: 'Fiscal period UUID (default: most recent)' }, + }, + }, + annotations: { + readOnlyHint: true, + destructiveHint: false, + idempotentHint: true, + openWorldHint: false, + }, + async execute(args, userId, supabase) { + let periodId = args.period_id as string | undefined + + if (!periodId) { + const { data: periods } = await supabase + .from('fiscal_periods') + .select('id') + .eq('user_id', userId) + .order('period_start', { ascending: false }) + .limit(1) + .single() + + if (!periods) { + throw new Error('No fiscal periods found. Categorize some transactions first.') + } + periodId = periods.id + } + + // Verify period belongs to user + const { data: period } = await supabase + .from('fiscal_periods') + .select('id, name, period_start, period_end') + .eq('id', periodId) + .eq('user_id', userId) + .single() + + if (!period) throw new Error('Fiscal period not found.') + + // Run queries in parallel (same as the KPI API route) + const [incomeStatement, trialBalance, arLedger, monthlyBreakdown, paidInvoices] = + await Promise.all([ + generateIncomeStatement(supabase, userId, periodId!), + generateTrialBalance(supabase, userId, periodId!), + generateARLedger(supabase, userId), + generateMonthlyBreakdown(supabase, userId, periodId!), + supabase + .from('invoices') + .select('invoice_date, paid_at') + .eq('user_id', userId) + .eq('status', 'paid') + .not('paid_at', 'is', null), + ]) + + const grossMargin = calculateGrossMargin(incomeStatement) + const cashPosition = calculateCashPosition(trialBalance.rows) + const expenseRatio = calculateExpenseRatio(incomeStatement) + const avgPaymentDays = calculateAvgPaymentDays( + (paidInvoices.data ?? []) as { invoice_date: string; paid_at: string }[] + ) + + // AR ledger uses entries, each with invoices that have outstanding amounts + const outstandingReceivables = arLedger.total_outstanding + const overdueReceivables = arLedger.total_overdue + + // VAT liability from trial balance + const getClosing = (accNum: string) => { + const row = trialBalance.rows.find((r) => r.account_number === accNum) + if (!row) return 0 + return row.closing_credit - row.closing_debit + } + const vatLiability = Math.round( + (getClosing('2611') + getClosing('2621') + getClosing('2631') - + getClosing('2641') - getClosing('2645')) * 100 + ) / 100 + + return { + period_name: period.name, + period_start: period.period_start, + period_end: period.period_end, + gross_margin: grossMargin, + net_result: incomeStatement.net_result, + cash_position: cashPosition, + outstanding_receivables: Math.round(outstandingReceivables * 100) / 100, + overdue_receivables: Math.round(overdueReceivables * 100) / 100, + expense_ratio: expenseRatio, + avg_payment_days: avgPaymentDays, + paid_invoice_count: paidInvoices.data?.length ?? 0, + vat_liability: vatLiability, + total_revenue: incomeStatement.total_revenue, + total_expenses: incomeStatement.total_expenses, + months: monthlyBreakdown.months, + } + }, + }, + + { + name: 'gnubok_get_income_statement', + description: + 'Get the income statement (resultatrΓ€kning) for a fiscal period. Shows revenue, expenses, ' + + 'and net result broken down by account category.\n\n' + + 'Args:\n' + + ' - period_id (string, optional): Fiscal period UUID. If omitted, uses the most recent period.\n\n' + + 'Returns JSON:\n' + + ' { revenue_sections, total_revenue, expense_sections, total_expenses, net_result,\n' + + ' period: { start, end } }\n\n' + + 'Examples:\n' + + ' - "What is my profit this year?" β†’ call with no args\n' + + ' - "Show my income statement" β†’ call with no args', + inputSchema: { + type: 'object', + properties: { + period_id: { type: 'string', description: 'Fiscal period UUID (default: most recent)' }, + }, + }, + annotations: { + readOnlyHint: true, + destructiveHint: false, + idempotentHint: true, + openWorldHint: false, + }, + async execute(args, userId, supabase) { + let periodId = args.period_id as string | undefined + + if (!periodId) { + const { data: periods } = await supabase + .from('fiscal_periods') + .select('id') + .eq('user_id', userId) + .order('period_start', { ascending: false }) + .limit(1) + .single() + + if (!periods) { + throw new Error('No fiscal periods found. Categorize some transactions first.') + } + periodId = periods.id + } + + const { data: period } = await supabase + .from('fiscal_periods') + .select('id, name, period_start, period_end') + .eq('id', periodId) + .eq('user_id', userId) + .single() + + if (!period) throw new Error('Fiscal period not found.') + + const result = await generateIncomeStatement(supabase, userId, periodId!) + result.period = { start: period.period_start, end: period.period_end } + + return { + period_name: period.name, + ...result, + } + }, + }, +] + +// ── MCP Protocol Handler ───────────────────────────────────── + +const SERVER_INFO = { + name: 'gnubok', + version: '1.0.0', +} + +const PROTOCOL_VERSION = '2025-03-26' + +function jsonRpc(id: string | number | null, result: unknown): JsonRpcResponse { + return { jsonrpc: '2.0', id, result } +} + +function jsonRpcError( + id: string | number | null, + code: number, + message: string, + data?: unknown +): JsonRpcResponse { + return { jsonrpc: '2.0', id, error: { code, message, data } } +} + +/** + * Handle an MCP JSON-RPC request. + * Auth is done via Bearer API key (extension route has skipAuth: true). + */ +export async function handleMcpRequest(request: Request): Promise { + // ── Auth ── + const appUrl = process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000' + const wwwAuth = `Bearer resource_metadata="${appUrl}/.well-known/oauth-protected-resource"` + + const token = extractBearerToken(request) + if (!token) { + return new Response( + JSON.stringify(jsonRpcError(null, -32000, 'Authorization required')), + { status: 401, headers: { 'Content-Type': 'application/json', 'WWW-Authenticate': wwwAuth } } + ) + } + + const authResult = await validateApiKey(token) + if ('error' in authResult) { + const status = authResult.status + const headers: Record = { 'Content-Type': 'application/json' } + if (status === 401) headers['WWW-Authenticate'] = wwwAuth + return new Response( + JSON.stringify(jsonRpcError(null, -32000, authResult.error)), + { status, headers } + ) + } + + const { userId } = authResult + const supabase = createServiceClientNoCookies() + + // ── Parse JSON-RPC ── + let body: JsonRpcRequest + try { + body = await request.json() + } catch { + return NextResponse.json( + jsonRpcError(null, -32700, 'Parse error: expected JSON-RPC 2.0 request body'), + { status: 400 } + ) + } + + if (body.jsonrpc !== '2.0' || !body.method) { + return NextResponse.json( + jsonRpcError(body.id ?? null, -32600, 'Invalid Request: must include jsonrpc="2.0" and method'), + { status: 400 } + ) + } + + // ── Dispatch ── + const { method, id, params } = body + + switch (method) { + case 'initialize': + return NextResponse.json( + jsonRpc(id ?? null, { + protocolVersion: PROTOCOL_VERSION, + capabilities: { + tools: { listChanged: false }, + }, + serverInfo: SERVER_INFO, + }) + ) + + case 'notifications/initialized': + // Client acknowledgement β€” no response needed for notifications + return new Response(null, { status: 204 }) + + case 'ping': + return NextResponse.json(jsonRpc(id ?? null, {})) + + case 'tools/list': + return NextResponse.json( + jsonRpc(id ?? null, { + tools: tools.map((t) => ({ + name: t.name, + description: t.description, + inputSchema: t.inputSchema, + annotations: t.annotations, + })), + }) + ) + + case 'tools/call': { + const toolName = (params as Record)?.name as string + const toolArgs = ((params as Record)?.arguments ?? {}) as Record< + string, + unknown + > + + const tool = tools.find((t) => t.name === toolName) + if (!tool) { + const available = tools.map((t) => t.name).join(', ') + return NextResponse.json( + jsonRpcError(id ?? null, -32602, `Unknown tool: "${toolName}". Available tools: ${available}`) + ) + } + + try { + const result = await tool.execute(toolArgs, userId, supabase) + return NextResponse.json( + jsonRpc(id ?? null, { + content: [{ type: 'text', text: JSON.stringify(result, null, 2) }], + }) + ) + } catch (err) { + const message = err instanceof Error ? err.message : 'Tool execution failed' + return NextResponse.json( + jsonRpc(id ?? null, { + content: [{ type: 'text', text: JSON.stringify({ error: message }) }], + isError: true, + }) + ) + } + } + + default: + return NextResponse.json( + jsonRpcError(id ?? null, -32601, `Method not found: "${method}"`) + ) + } +} diff --git a/lib/auth/api-keys.ts b/lib/auth/api-keys.ts new file mode 100644 index 00000000..8cea3c7f --- /dev/null +++ b/lib/auth/api-keys.ts @@ -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 } +} diff --git a/lib/auth/oauth-codes.ts b/lib/auth/oauth-codes.ts new file mode 100644 index 00000000..0f8a8e33 --- /dev/null +++ b/lib/auth/oauth-codes.ts @@ -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): 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') +} diff --git a/lib/extensions/__tests__/sectors.test.ts b/lib/extensions/__tests__/sectors.test.ts index 5ddabe75..d5a1b70b 100644 --- a/lib/extensions/__tests__/sectors.test.ts +++ b/lib/extensions/__tests__/sectors.test.ts @@ -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', () => { diff --git a/lib/extensions/_generated/enabled-extensions.ts b/lib/extensions/_generated/enabled-extensions.ts index 4fdf262b..3109d694 100644 --- a/lib/extensions/_generated/enabled-extensions.ts +++ b/lib/extensions/_generated/enabled-extensions.ts @@ -5,4 +5,5 @@ export const ENABLED_EXTENSION_IDS: ReadonlySet = new Set([ 'email', 'arcim-migration', 'tic', + 'mcp-server', ]) diff --git a/lib/extensions/_generated/extension-list.ts b/lib/extensions/_generated/extension-list.ts index ea8ab576..53822df0 100644 --- a/lib/extensions/_generated/extension-list.ts +++ b/lib/extensions/_generated/extension-list.ts @@ -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, ] diff --git a/lib/extensions/_generated/sector-definitions.ts b/lib/extensions/_generated/sector-definitions.ts index d009998d..151da4ab 100644 --- a/lib/extensions/_generated/sector-definitions.ts +++ b/lib/extensions/_generated/sector-definitions.ts @@ -58,5 +58,15 @@ export const EXTENSION_DEFINITIONS: Record = { "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." + }, ], } diff --git a/lib/reports/__tests__/kpi.test.ts b/lib/reports/__tests__/kpi.test.ts new file mode 100644 index 00000000..14717b16 --- /dev/null +++ b/lib/reports/__tests__/kpi.test.ts @@ -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 { + 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 { + 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) + }) +}) diff --git a/lib/reports/kpi.ts b/lib/reports/kpi.ts new file mode 100644 index 00000000..53c04835 --- /dev/null +++ b/lib/reports/kpi.ts @@ -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) +} diff --git a/scripts/mcp-bridge.mjs b/scripts/mcp-bridge.mjs new file mode 100644 index 00000000..e69addc0 --- /dev/null +++ b/scripts/mcp-bridge.mjs @@ -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') + } + } +} diff --git a/supabase/migrations/20260320120000_api_keys.sql b/supabase/migrations/20260320120000_api_keys.sql new file mode 100644 index 00000000..afd5d646 --- /dev/null +++ b/supabase/migrations/20260320120000_api_keys.sql @@ -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; +$$; diff --git a/supabase/migrations/20260321120000_oauth_used_codes.sql b/supabase/migrations/20260321120000_oauth_used_codes.sql new file mode 100644 index 00000000..618d6407 --- /dev/null +++ b/supabase/migrations/20260321120000_oauth_used_codes.sql @@ -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); diff --git a/types/index.ts b/types/index.ts index aef3fc96..0c5e4939 100644 --- a/types/index.ts +++ b/types/index.ts @@ -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 } +}