feat: MCP server, API keys, OAuth, and KPI dashboard (#72)

* fix: prevent Chrome auto-translate from crashing React during onboarding

Chrome auto-translate modifies DOM text nodes when it detects a Swedish
page (lang="sv") in a browser set to English. React does not expect
external DOM mutations and throws, crashing the entire component tree
into global-error.tsx on every step transition.

Add translate="no" and <meta name="google" content="notranslate"> to
suppress browser translation. Also fix timezone-unsafe date parsing in
fiscal period validation (new Date("YYYY-MM-DD") + getDate() returns
local-timezone values, shifting dates by -1 day in Western timezones).

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>

* fix: add notranslate meta tag to global-error.tsx for consistency

Per review feedback — global-error.tsx renders its own <html> document,
so it needs the same <meta name="google" content="notranslate"> tag as
layout.tsx to fully suppress Chrome translation on error pages.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>

* feat: add MCP server extension with OAuth, API keys, and KPI dashboard

Let users do bookkeeping through Claude Desktop, Claude Code, or any
MCP-compatible client. "Show my uncategorized transactions." "Book that
as office supplies." "Invoice Acme for 15,000 kr."

MCP server (extension):
- 10 tools: transactions, categorization, customers, invoices,
  trial balance, VAT report, KPI report, income statement
- JSON-RPC 2.0 protocol (no SDK dependency, works in serverless)
- Tool annotations, pagination, input validation per MCP best practices
- Same engine as web UI (VAT rules, exchange rates, event emission)

API key infrastructure (core):
- api_keys table with RLS, rate limiting (100 RPM), scopes column
- Atomic rate limit via DB RPC (validate_and_increment_api_key)
- Key management API routes + settings UI panel

OAuth 2.1 for Claude Desktop connectors:
- .well-known/oauth-protected-resource + oauth-authorization-server
- Authorization endpoint with consent page
- Token endpoint with PKCE verification
- Stateless encrypted auth codes (AES-256-GCM, no DB storage)
- Dynamic client registration

KPI dashboard:
- /nyckeltal page with hero cards, operational grid, trend chart
- GET /api/reports/kpi endpoint
- Gross margin, cash position, expense ratio, avg payment days,
  VAT liability, revenue/expense trend

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>

* fix: address OAuth security vulnerabilities from code review

Critical fixes:
- Auth code replay: Track used codes in oauth_used_codes table with
  unique constraint. Codes are single-use per OAuth 2.1 §4.1.2.
- Open redirect: Validate redirect_uri against hardcoded allowlist
  of known Claude callback URLs + localhost for dev.

P1 fixes:
- Move API key creation from /authorize to /token endpoint. Keys are
  only created after PKCE verification, preventing orphaned keys on
  abandoned OAuth flows.
- Add ensureInitialized() to MCP server so event handlers load and
  transaction.categorized events reach extensions.

P2 fixes:
- Remove 'plain' from PKCE methods — only S256 is advertised and
  accepted.
- Fix extension count in sectors test (10 → 11 for mcp-server).

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>

* fix: remove duplicate ensureInitialized() that caused circular import

The extension router (ext/[...path]/route.ts) already calls
ensureInitialized() before dispatching to handlers. The duplicate
call in server.ts created a circular import that Turbopack couldn't
resolve, breaking the Vercel build.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
This commit is contained in:
Jakob Wennberg
2026-03-21 12:57:14 +01:00
committed by GitHub
co-authored by Claude Opus 4.6
parent 2b75ef6538
commit 5d66dd6bfc
41 changed files with 6742 additions and 4 deletions
+236
View File
@@ -0,0 +1,236 @@
---
name: mcp-builder
description: Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when building MCP servers to integrate external APIs or services, whether in Python (FastMCP) or Node/TypeScript (MCP SDK).
license: Complete terms in LICENSE.txt
---
# MCP Server Development Guide
## Overview
Create MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. The quality of an MCP server is measured by how well it enables LLMs to accomplish real-world tasks.
---
# Process
## 🚀 High-Level Workflow
Creating a high-quality MCP server involves four main phases:
### Phase 1: Deep Research and Planning
#### 1.1 Understand Modern MCP Design
**API Coverage vs. Workflow Tools:**
Balance comprehensive API endpoint coverage with specialized workflow tools. Workflow tools can be more convenient for specific tasks, while comprehensive coverage gives agents flexibility to compose operations. Performance varies by client—some clients benefit from code execution that combines basic tools, while others work better with higher-level workflows. When uncertain, prioritize comprehensive API coverage.
**Tool Naming and Discoverability:**
Clear, descriptive tool names help agents find the right tools quickly. Use consistent prefixes (e.g., `github_create_issue`, `github_list_repos`) and action-oriented naming.
**Context Management:**
Agents benefit from concise tool descriptions and the ability to filter/paginate results. Design tools that return focused, relevant data. Some clients support code execution which can help agents filter and process data efficiently.
**Actionable Error Messages:**
Error messages should guide agents toward solutions with specific suggestions and next steps.
#### 1.2 Study MCP Protocol Documentation
**Navigate the MCP specification:**
Start with the sitemap to find relevant pages: `https://modelcontextprotocol.io/sitemap.xml`
Then fetch specific pages with `.md` suffix for markdown format (e.g., `https://modelcontextprotocol.io/specification/draft.md`).
Key pages to review:
- Specification overview and architecture
- Transport mechanisms (streamable HTTP, stdio)
- Tool, resource, and prompt definitions
#### 1.3 Study Framework Documentation
**Recommended stack:**
- **Language**: TypeScript (high-quality SDK support and good compatibility in many execution environments e.g. MCPB. Plus AI models are good at generating TypeScript code, benefiting from its broad usage, static typing and good linting tools)
- **Transport**: Streamable HTTP for remote servers, using stateless JSON (simpler to scale and maintain, as opposed to stateful sessions and streaming responses). stdio for local servers.
**Load framework documentation:**
- **MCP Best Practices**: [📋 View Best Practices](./reference/mcp_best_practices.md) - Core guidelines
**For TypeScript (recommended):**
- **TypeScript SDK**: Use WebFetch to load `https://raw.githubusercontent.com/modelcontextprotocol/typescript-sdk/main/README.md`
- [⚡ TypeScript Guide](./reference/node_mcp_server.md) - TypeScript patterns and examples
**For Python:**
- **Python SDK**: Use WebFetch to load `https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/main/README.md`
- [🐍 Python Guide](./reference/python_mcp_server.md) - Python patterns and examples
#### 1.4 Plan Your Implementation
**Understand the API:**
Review the service's API documentation to identify key endpoints, authentication requirements, and data models. Use web search and WebFetch as needed.
**Tool Selection:**
Prioritize comprehensive API coverage. List endpoints to implement, starting with the most common operations.
---
### Phase 2: Implementation
#### 2.1 Set Up Project Structure
See language-specific guides for project setup:
- [⚡ TypeScript Guide](./reference/node_mcp_server.md) - Project structure, package.json, tsconfig.json
- [🐍 Python Guide](./reference/python_mcp_server.md) - Module organization, dependencies
#### 2.2 Implement Core Infrastructure
Create shared utilities:
- API client with authentication
- Error handling helpers
- Response formatting (JSON/Markdown)
- Pagination support
#### 2.3 Implement Tools
For each tool:
**Input Schema:**
- Use Zod (TypeScript) or Pydantic (Python)
- Include constraints and clear descriptions
- Add examples in field descriptions
**Output Schema:**
- Define `outputSchema` where possible for structured data
- Use `structuredContent` in tool responses (TypeScript SDK feature)
- Helps clients understand and process tool outputs
**Tool Description:**
- Concise summary of functionality
- Parameter descriptions
- Return type schema
**Implementation:**
- Async/await for I/O operations
- Proper error handling with actionable messages
- Support pagination where applicable
- Return both text content and structured data when using modern SDKs
**Annotations:**
- `readOnlyHint`: true/false
- `destructiveHint`: true/false
- `idempotentHint`: true/false
- `openWorldHint`: true/false
---
### Phase 3: Review and Test
#### 3.1 Code Quality
Review for:
- No duplicated code (DRY principle)
- Consistent error handling
- Full type coverage
- Clear tool descriptions
#### 3.2 Build and Test
**TypeScript:**
- Run `npm run build` to verify compilation
- Test with MCP Inspector: `npx @modelcontextprotocol/inspector`
**Python:**
- Verify syntax: `python -m py_compile your_server.py`
- Test with MCP Inspector
See language-specific guides for detailed testing approaches and quality checklists.
---
### Phase 4: Create Evaluations
After implementing your MCP server, create comprehensive evaluations to test its effectiveness.
**Load [✅ Evaluation Guide](./reference/evaluation.md) for complete evaluation guidelines.**
#### 4.1 Understand Evaluation Purpose
Use evaluations to test whether LLMs can effectively use your MCP server to answer realistic, complex questions.
#### 4.2 Create 10 Evaluation Questions
To create effective evaluations, follow the process outlined in the evaluation guide:
1. **Tool Inspection**: List available tools and understand their capabilities
2. **Content Exploration**: Use READ-ONLY operations to explore available data
3. **Question Generation**: Create 10 complex, realistic questions
4. **Answer Verification**: Solve each question yourself to verify answers
#### 4.3 Evaluation Requirements
Ensure each question is:
- **Independent**: Not dependent on other questions
- **Read-only**: Only non-destructive operations required
- **Complex**: Requiring multiple tool calls and deep exploration
- **Realistic**: Based on real use cases humans would care about
- **Verifiable**: Single, clear answer that can be verified by string comparison
- **Stable**: Answer won't change over time
#### 4.4 Output Format
Create an XML file with this structure:
```xml
<evaluation>
<qa_pair>
<question>Find discussions about AI model launches with animal codenames. One model needed a specific safety designation that uses the format ASL-X. What number X was being determined for the model named after a spotted wild cat?</question>
<answer>3</answer>
</qa_pair>
<!-- More qa_pairs... -->
</evaluation>
```
---
# Reference Files
## 📚 Documentation Library
Load these resources as needed during development:
### Core MCP Documentation (Load First)
- **MCP Protocol**: Start with sitemap at `https://modelcontextprotocol.io/sitemap.xml`, then fetch specific pages with `.md` suffix
- [📋 MCP Best Practices](./reference/mcp_best_practices.md) - Universal MCP guidelines including:
- Server and tool naming conventions
- Response format guidelines (JSON vs Markdown)
- Pagination best practices
- Transport selection (streamable HTTP vs stdio)
- Security and error handling standards
### SDK Documentation (Load During Phase 1/2)
- **Python SDK**: Fetch from `https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/main/README.md`
- **TypeScript SDK**: Fetch from `https://raw.githubusercontent.com/modelcontextprotocol/typescript-sdk/main/README.md`
### Language-Specific Implementation Guides (Load During Phase 2)
- [🐍 Python Implementation Guide](./reference/python_mcp_server.md) - Complete Python/FastMCP guide with:
- Server initialization patterns
- Pydantic model examples
- Tool registration with `@mcp.tool`
- Complete working examples
- Quality checklist
- [⚡ TypeScript Implementation Guide](./reference/node_mcp_server.md) - Complete TypeScript guide with:
- Project structure
- Zod schema patterns
- Tool registration with `server.registerTool`
- Complete working examples
- Quality checklist
### Evaluation Guide (Load During Phase 4)
- [✅ Evaluation Guide](./reference/evaluation.md) - Complete evaluation creation guide with:
- Question creation guidelines
- Answer verification strategies
- XML format specifications
- Example questions and answers
- Running an evaluation with the provided scripts
File diff suppressed because it is too large Load Diff
@@ -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
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,151 @@
"""Lightweight connection handling for MCP servers."""
from abc import ABC, abstractmethod
from contextlib import AsyncExitStack
from typing import Any
from mcp import ClientSession, StdioServerParameters
from mcp.client.sse import sse_client
from mcp.client.stdio import stdio_client
from mcp.client.streamable_http import streamablehttp_client
class MCPConnection(ABC):
"""Base class for MCP server connections."""
def __init__(self):
self.session = None
self._stack = None
@abstractmethod
def _create_context(self):
"""Create the connection context based on connection type."""
async def __aenter__(self):
"""Initialize MCP server connection."""
self._stack = AsyncExitStack()
await self._stack.__aenter__()
try:
ctx = self._create_context()
result = await self._stack.enter_async_context(ctx)
if len(result) == 2:
read, write = result
elif len(result) == 3:
read, write, _ = result
else:
raise ValueError(f"Unexpected context result: {result}")
session_ctx = ClientSession(read, write)
self.session = await self._stack.enter_async_context(session_ctx)
await self.session.initialize()
return self
except BaseException:
await self._stack.__aexit__(None, None, None)
raise
async def __aexit__(self, exc_type, exc_val, exc_tb):
"""Clean up MCP server connection resources."""
if self._stack:
await self._stack.__aexit__(exc_type, exc_val, exc_tb)
self.session = None
self._stack = None
async def list_tools(self) -> list[dict[str, Any]]:
"""Retrieve available tools from the MCP server."""
response = await self.session.list_tools()
return [
{
"name": tool.name,
"description": tool.description,
"input_schema": tool.inputSchema,
}
for tool in response.tools
]
async def call_tool(self, tool_name: str, arguments: dict[str, Any]) -> Any:
"""Call a tool on the MCP server with provided arguments."""
result = await self.session.call_tool(tool_name, arguments=arguments)
return result.content
class MCPConnectionStdio(MCPConnection):
"""MCP connection using standard input/output."""
def __init__(self, command: str, args: list[str] = None, env: dict[str, str] = None):
super().__init__()
self.command = command
self.args = args or []
self.env = env
def _create_context(self):
return stdio_client(
StdioServerParameters(command=self.command, args=self.args, env=self.env)
)
class MCPConnectionSSE(MCPConnection):
"""MCP connection using Server-Sent Events."""
def __init__(self, url: str, headers: dict[str, str] = None):
super().__init__()
self.url = url
self.headers = headers or {}
def _create_context(self):
return sse_client(url=self.url, headers=self.headers)
class MCPConnectionHTTP(MCPConnection):
"""MCP connection using Streamable HTTP."""
def __init__(self, url: str, headers: dict[str, str] = None):
super().__init__()
self.url = url
self.headers = headers or {}
def _create_context(self):
return streamablehttp_client(url=self.url, headers=self.headers)
def create_connection(
transport: str,
command: str = None,
args: list[str] = None,
env: dict[str, str] = None,
url: str = None,
headers: dict[str, str] = None,
) -> MCPConnection:
"""Factory function to create the appropriate MCP connection.
Args:
transport: Connection type ("stdio", "sse", or "http")
command: Command to run (stdio only)
args: Command arguments (stdio only)
env: Environment variables (stdio only)
url: Server URL (sse and http only)
headers: HTTP headers (sse and http only)
Returns:
MCPConnection instance
"""
transport = transport.lower()
if transport == "stdio":
if not command:
raise ValueError("Command is required for stdio transport")
return MCPConnectionStdio(command=command, args=args, env=env)
elif transport == "sse":
if not url:
raise ValueError("URL is required for sse transport")
return MCPConnectionSSE(url=url, headers=headers)
elif transport in ["http", "streamable_http", "streamable-http"]:
if not url:
raise ValueError("URL is required for http transport")
return MCPConnectionHTTP(url=url, headers=headers)
else:
raise ValueError(f"Unsupported transport type: {transport}. Use 'stdio', 'sse', or 'http'")
@@ -0,0 +1,373 @@
"""MCP Server Evaluation Harness
This script evaluates MCP servers by running test questions against them using Claude.
"""
import argparse
import asyncio
import json
import re
import sys
import time
import traceback
import xml.etree.ElementTree as ET
from pathlib import Path
from typing import Any
from anthropic import Anthropic
from connections import create_connection
EVALUATION_PROMPT = """You are an AI assistant with access to tools.
When given a task, you MUST:
1. Use the available tools to complete the task
2. Provide summary of each step in your approach, wrapped in <summary> tags
3. Provide feedback on the tools provided, wrapped in <feedback> tags
4. Provide your final response, wrapped in <response> tags
Summary Requirements:
- In your <summary> tags, you must explain:
- The steps you took to complete the task
- Which tools you used, in what order, and why
- The inputs you provided to each tool
- The outputs you received from each tool
- A summary for how you arrived at the response
Feedback Requirements:
- In your <feedback> tags, provide constructive feedback on the tools:
- Comment on tool names: Are they clear and descriptive?
- Comment on input parameters: Are they well-documented? Are required vs optional parameters clear?
- Comment on descriptions: Do they accurately describe what the tool does?
- Comment on any errors encountered during tool usage: Did the tool fail to execute? Did the tool return too many tokens?
- Identify specific areas for improvement and explain WHY they would help
- Be specific and actionable in your suggestions
Response Requirements:
- Your response should be concise and directly address what was asked
- Always wrap your final response in <response> tags
- If you cannot solve the task return <response>NOT_FOUND</response>
- For numeric responses, provide just the number
- For IDs, provide just the ID
- For names or text, provide the exact text requested
- Your response should go last"""
def parse_evaluation_file(file_path: Path) -> list[dict[str, Any]]:
"""Parse XML evaluation file with qa_pair elements."""
try:
tree = ET.parse(file_path)
root = tree.getroot()
evaluations = []
for qa_pair in root.findall(".//qa_pair"):
question_elem = qa_pair.find("question")
answer_elem = qa_pair.find("answer")
if question_elem is not None and answer_elem is not None:
evaluations.append({
"question": (question_elem.text or "").strip(),
"answer": (answer_elem.text or "").strip(),
})
return evaluations
except Exception as e:
print(f"Error parsing evaluation file {file_path}: {e}")
return []
def extract_xml_content(text: str, tag: str) -> str | None:
"""Extract content from XML tags."""
pattern = rf"<{tag}>(.*?)</{tag}>"
matches = re.findall(pattern, text, re.DOTALL)
return matches[-1].strip() if matches else None
async def agent_loop(
client: Anthropic,
model: str,
question: str,
tools: list[dict[str, Any]],
connection: Any,
) -> tuple[str, dict[str, Any]]:
"""Run the agent loop with MCP tools."""
messages = [{"role": "user", "content": question}]
response = await asyncio.to_thread(
client.messages.create,
model=model,
max_tokens=4096,
system=EVALUATION_PROMPT,
messages=messages,
tools=tools,
)
messages.append({"role": "assistant", "content": response.content})
tool_metrics = {}
while response.stop_reason == "tool_use":
tool_use = next(block for block in response.content if block.type == "tool_use")
tool_name = tool_use.name
tool_input = tool_use.input
tool_start_ts = time.time()
try:
tool_result = await connection.call_tool(tool_name, tool_input)
tool_response = json.dumps(tool_result) if isinstance(tool_result, (dict, list)) else str(tool_result)
except Exception as e:
tool_response = f"Error executing tool {tool_name}: {str(e)}\n"
tool_response += traceback.format_exc()
tool_duration = time.time() - tool_start_ts
if tool_name not in tool_metrics:
tool_metrics[tool_name] = {"count": 0, "durations": []}
tool_metrics[tool_name]["count"] += 1
tool_metrics[tool_name]["durations"].append(tool_duration)
messages.append({
"role": "user",
"content": [{
"type": "tool_result",
"tool_use_id": tool_use.id,
"content": tool_response,
}]
})
response = await asyncio.to_thread(
client.messages.create,
model=model,
max_tokens=4096,
system=EVALUATION_PROMPT,
messages=messages,
tools=tools,
)
messages.append({"role": "assistant", "content": response.content})
response_text = next(
(block.text for block in response.content if hasattr(block, "text")),
None,
)
return response_text, tool_metrics
async def evaluate_single_task(
client: Anthropic,
model: str,
qa_pair: dict[str, Any],
tools: list[dict[str, Any]],
connection: Any,
task_index: int,
) -> dict[str, Any]:
"""Evaluate a single QA pair with the given tools."""
start_time = time.time()
print(f"Task {task_index + 1}: Running task with question: {qa_pair['question']}")
response, tool_metrics = await agent_loop(client, model, qa_pair["question"], tools, connection)
response_value = extract_xml_content(response, "response")
summary = extract_xml_content(response, "summary")
feedback = extract_xml_content(response, "feedback")
duration_seconds = time.time() - start_time
return {
"question": qa_pair["question"],
"expected": qa_pair["answer"],
"actual": response_value,
"score": int(response_value == qa_pair["answer"]) if response_value else 0,
"total_duration": duration_seconds,
"tool_calls": tool_metrics,
"num_tool_calls": sum(len(metrics["durations"]) for metrics in tool_metrics.values()),
"summary": summary,
"feedback": feedback,
}
REPORT_HEADER = """
# Evaluation Report
## Summary
- **Accuracy**: {correct}/{total} ({accuracy:.1f}%)
- **Average Task Duration**: {average_duration_s:.2f}s
- **Average Tool Calls per Task**: {average_tool_calls:.2f}
- **Total Tool Calls**: {total_tool_calls}
---
"""
TASK_TEMPLATE = """
### Task {task_num}
**Question**: {question}
**Ground Truth Answer**: `{expected_answer}`
**Actual Answer**: `{actual_answer}`
**Correct**: {correct_indicator}
**Duration**: {total_duration:.2f}s
**Tool Calls**: {tool_calls}
**Summary**
{summary}
**Feedback**
{feedback}
---
"""
async def run_evaluation(
eval_path: Path,
connection: Any,
model: str = "claude-3-7-sonnet-20250219",
) -> str:
"""Run evaluation with MCP server tools."""
print("🚀 Starting Evaluation")
client = Anthropic()
tools = await connection.list_tools()
print(f"📋 Loaded {len(tools)} tools from MCP server")
qa_pairs = parse_evaluation_file(eval_path)
print(f"📋 Loaded {len(qa_pairs)} evaluation tasks")
results = []
for i, qa_pair in enumerate(qa_pairs):
print(f"Processing task {i + 1}/{len(qa_pairs)}")
result = await evaluate_single_task(client, model, qa_pair, tools, connection, i)
results.append(result)
correct = sum(r["score"] for r in results)
accuracy = (correct / len(results)) * 100 if results else 0
average_duration_s = sum(r["total_duration"] for r in results) / len(results) if results else 0
average_tool_calls = sum(r["num_tool_calls"] for r in results) / len(results) if results else 0
total_tool_calls = sum(r["num_tool_calls"] for r in results)
report = REPORT_HEADER.format(
correct=correct,
total=len(results),
accuracy=accuracy,
average_duration_s=average_duration_s,
average_tool_calls=average_tool_calls,
total_tool_calls=total_tool_calls,
)
report += "".join([
TASK_TEMPLATE.format(
task_num=i + 1,
question=qa_pair["question"],
expected_answer=qa_pair["answer"],
actual_answer=result["actual"] or "N/A",
correct_indicator="✅" if result["score"] else "❌",
total_duration=result["total_duration"],
tool_calls=json.dumps(result["tool_calls"], indent=2),
summary=result["summary"] or "N/A",
feedback=result["feedback"] or "N/A",
)
for i, (qa_pair, result) in enumerate(zip(qa_pairs, results))
])
return report
def parse_headers(header_list: list[str]) -> dict[str, str]:
"""Parse header strings in format 'Key: Value' into a dictionary."""
headers = {}
if not header_list:
return headers
for header in header_list:
if ":" in header:
key, value = header.split(":", 1)
headers[key.strip()] = value.strip()
else:
print(f"Warning: Ignoring malformed header: {header}")
return headers
def parse_env_vars(env_list: list[str]) -> dict[str, str]:
"""Parse environment variable strings in format 'KEY=VALUE' into a dictionary."""
env = {}
if not env_list:
return env
for env_var in env_list:
if "=" in env_var:
key, value = env_var.split("=", 1)
env[key.strip()] = value.strip()
else:
print(f"Warning: Ignoring malformed environment variable: {env_var}")
return env
async def main():
parser = argparse.ArgumentParser(
description="Evaluate MCP servers using test questions",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
# Evaluate a local stdio MCP server
python evaluation.py -t stdio -c python -a my_server.py eval.xml
# Evaluate an SSE MCP server
python evaluation.py -t sse -u https://example.com/mcp -H "Authorization: Bearer token" eval.xml
# Evaluate an HTTP MCP server with custom model
python evaluation.py -t http -u https://example.com/mcp -m claude-3-5-sonnet-20241022 eval.xml
""",
)
parser.add_argument("eval_file", type=Path, help="Path to evaluation XML file")
parser.add_argument("-t", "--transport", choices=["stdio", "sse", "http"], default="stdio", help="Transport type (default: stdio)")
parser.add_argument("-m", "--model", default="claude-3-7-sonnet-20250219", help="Claude model to use (default: claude-3-7-sonnet-20250219)")
stdio_group = parser.add_argument_group("stdio options")
stdio_group.add_argument("-c", "--command", help="Command to run MCP server (stdio only)")
stdio_group.add_argument("-a", "--args", nargs="+", help="Arguments for the command (stdio only)")
stdio_group.add_argument("-e", "--env", nargs="+", help="Environment variables in KEY=VALUE format (stdio only)")
remote_group = parser.add_argument_group("sse/http options")
remote_group.add_argument("-u", "--url", help="MCP server URL (sse/http only)")
remote_group.add_argument("-H", "--header", nargs="+", dest="headers", help="HTTP headers in 'Key: Value' format (sse/http only)")
parser.add_argument("-o", "--output", type=Path, help="Output file for evaluation report (default: stdout)")
args = parser.parse_args()
if not args.eval_file.exists():
print(f"Error: Evaluation file not found: {args.eval_file}")
sys.exit(1)
headers = parse_headers(args.headers) if args.headers else None
env_vars = parse_env_vars(args.env) if args.env else None
try:
connection = create_connection(
transport=args.transport,
command=args.command,
args=args.args,
env=env_vars,
url=args.url,
headers=headers,
)
except ValueError as e:
print(f"Error: {e}")
sys.exit(1)
print(f"🔗 Connecting to MCP server via {args.transport}...")
async with connection:
print("✅ Connected successfully")
report = await run_evaluation(args.eval_file, connection, args.model)
if args.output:
args.output.write_text(report)
print(f"\n✅ Report saved to {args.output}")
else:
print("\n" + report)
if __name__ == "__main__":
asyncio.run(main())
@@ -0,0 +1,22 @@
<evaluation>
<qa_pair>
<question>Calculate the compound interest on $10,000 invested at 5% annual interest rate, compounded monthly for 3 years. What is the final amount in dollars (rounded to 2 decimal places)?</question>
<answer>11614.72</answer>
</qa_pair>
<qa_pair>
<question>A projectile is launched at a 45-degree angle with an initial velocity of 50 m/s. Calculate the total distance (in meters) it has traveled from the launch point after 2 seconds, assuming g=9.8 m/s². Round to 2 decimal places.</question>
<answer>87.25</answer>
</qa_pair>
<qa_pair>
<question>A sphere has a volume of 500 cubic meters. Calculate its surface area in square meters. Round to 2 decimal places.</question>
<answer>304.65</answer>
</qa_pair>
<qa_pair>
<question>Calculate the population standard deviation of this dataset: [12, 15, 18, 22, 25, 30, 35]. Round to 2 decimal places.</question>
<answer>7.61</answer>
</qa_pair>
<qa_pair>
<question>Calculate the pH of a solution with a hydrogen ion concentration of 3.5 × 10^-5 M. Round to 2 decimal places.</question>
<answer>4.46</answer>
</qa_pair>
</evaluation>
@@ -0,0 +1,2 @@
anthropic>=0.39.0
mcp>=1.1.0
+159
View File
@@ -0,0 +1,159 @@
'use client'
import { useState, useEffect } from 'react'
import { Label } from '@/components/ui/label'
import { Card, CardContent } from '@/components/ui/card'
import { KPIHeroCards } from '@/components/kpi/KPIHeroCards'
import { KPIOperationalGrid } from '@/components/kpi/KPIOperationalGrid'
import { KPITrendChart } from '@/components/kpi/KPITrendChart'
import type { FiscalPeriod, KPIReport } from '@/types'
export default function NyckeltalPage() {
const [periods, setPeriods] = useState<FiscalPeriod[]>([])
const [selectedPeriod, setSelectedPeriod] = useState('')
const [report, setReport] = useState<KPIReport | null>(null)
const [isLoadingInit, setIsLoadingInit] = useState(true)
const [isLoadingReport, setIsLoadingReport] = useState(false)
const [error, setError] = useState<string | null>(null)
useEffect(() => {
async function fetchPeriods() {
try {
const res = await fetch('/api/bookkeeping/fiscal-periods')
const { data } = await res.json()
setPeriods(data || [])
if (data && data.length > 0) {
setSelectedPeriod(data[0].id)
}
} catch {
setError('Kunde inte hämta räkenskapsår')
} finally {
setIsLoadingInit(false)
}
}
fetchPeriods()
}, [])
useEffect(() => {
if (!selectedPeriod) return
let cancelled = false
async function fetchReport() {
setIsLoadingReport(true)
setError(null)
try {
const res = await fetch(`/api/reports/kpi?period_id=${selectedPeriod}`)
if (!res.ok) throw new Error('Kunde inte hämta nyckeltal')
const { data } = await res.json()
if (!cancelled) setReport(data)
} catch {
if (!cancelled) setError('Kunde inte hämta nyckeltal')
} finally {
if (!cancelled) setIsLoadingReport(false)
}
}
fetchReport()
return () => { cancelled = true }
}, [selectedPeriod])
if (isLoadingInit) {
return (
<div className="space-y-6">
<div>
<h1 className="font-display text-2xl md:text-3xl font-medium tracking-tight">Nyckeltal</h1>
<p className="text-muted-foreground">Översikt av företagets ekonomiska hälsa</p>
</div>
<LoadingSkeleton />
</div>
)
}
return (
<div className="space-y-6">
<div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
<div>
<h1 className="font-display text-2xl md:text-3xl font-medium tracking-tight">Nyckeltal</h1>
<p className="text-muted-foreground">Översikt av företagets ekonomiska hälsa</p>
</div>
</div>
{/* Period selector */}
{periods.length > 0 && (
<div>
<Label>Räkenskapsår</Label>
<select
value={selectedPeriod}
onChange={(e) => setSelectedPeriod(e.target.value)}
className="w-full mt-1 max-w-xs rounded-md border border-input bg-background px-3 py-2 text-sm"
>
{periods.map((p) => (
<option key={p.id} value={p.id}>
{p.name} ({p.period_start} — {p.period_end})
</option>
))}
</select>
</div>
)}
{error && (
<Card>
<CardContent className="py-8 text-center text-muted-foreground">
<p>{error}</p>
</CardContent>
</Card>
)}
{isLoadingReport && <LoadingSkeleton />}
{!isLoadingReport && !error && report && (
<>
<KPIHeroCards report={report} />
<KPIOperationalGrid report={report} />
{report.months.length > 0 && <KPITrendChart months={report.months} />}
</>
)}
{!isLoadingReport && !error && !report && periods.length === 0 && (
<Card>
<CardContent className="py-12 text-center text-muted-foreground">
<p>Inget räkenskapsår hittades. Skapa ett räkenskapsår för att se nyckeltal.</p>
</CardContent>
</Card>
)}
</div>
)
}
function LoadingSkeleton() {
return (
<div className="space-y-6">
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
{[1, 2, 3, 4].map((i) => (
<Card key={i}>
<CardContent className="p-5 space-y-2">
<div className="h-3 bg-muted rounded w-20 animate-pulse" />
<div className="h-7 bg-muted rounded w-28 animate-pulse" />
<div className="h-3 bg-muted rounded w-16 animate-pulse" />
</CardContent>
</Card>
))}
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
{[1, 2, 3, 4].map((i) => (
<Card key={i}>
<CardContent className="p-5 space-y-2">
<div className="h-3 bg-muted rounded w-24 animate-pulse" />
<div className="h-6 bg-muted rounded w-20 animate-pulse" />
</CardContent>
</Card>
))}
</div>
<Card>
<CardContent className="p-5 space-y-3">
<div className="h-4 bg-muted rounded w-40 animate-pulse" />
<div className="h-56 bg-muted rounded animate-pulse" />
</CardContent>
</Card>
</div>
)
}
+10
View File
@@ -37,6 +37,7 @@ import { validateBankgiroNumber, formatBankgiroNumber } from '@/lib/bankgiro/luh
import { CalendarFeedSettings } from '@/components/settings/CalendarFeedSettings'
import { getSettingsPanel } from '@/lib/extensions/settings-panel-registry'
import { SecuritySettings } from '@/components/settings/SecuritySettings'
import { ApiKeysPanel } from '@/components/settings/ApiKeysPanel'
import { ENABLED_EXTENSION_IDS } from '@/lib/extensions/_generated/enabled-extensions'
const BankingPanel = getSettingsPanel('enable-banking')
@@ -52,6 +53,7 @@ export default function SettingsPage() {
const [settings, setSettings] = useState<CompanySettings | null>(null)
const hasBankingExtension = ENABLED_EXTENSION_IDS.has('enable-banking')
const hasCalendarExtension = ENABLED_EXTENSION_IDS.has('calendar')
const hasMcpExtension = ENABLED_EXTENSION_IDS.has('mcp-server')
const [bankConnectionError, setBankConnectionError] = useState<string | null>(null)
const [bankgiroError, setBankgiroError] = useState<string | null>(null)
const [showDeleteDialog, setShowDeleteDialog] = useState(false)
@@ -69,6 +71,7 @@ export default function SettingsPage() {
{ value: 'calendar', label: 'Kalender', show: hasCalendarExtension },
{ value: 'security', label: 'Säkerhet', show: true },
{ value: 'appearance', label: 'Utseende', show: true },
{ value: 'api', label: 'API', show: hasMcpExtension },
{ value: 'account', label: 'Konto', show: true },
].filter(t => t.show)
@@ -702,6 +705,13 @@ export default function SettingsPage() {
</Card>
</TabsContent>
{/* API keys */}
{hasMcpExtension && (
<TabsContent value="api">
<ApiKeysPanel />
</TabsContent>
)}
{/* Account settings */}
<TabsContent value="account" className="space-y-6">
<Card>
@@ -0,0 +1,21 @@
import { NextResponse } from 'next/server'
/**
* RFC 8414 — OAuth 2.0 Authorization Server Metadata.
* Tells MCP clients where the authorize/token endpoints are.
*/
export async function GET() {
const appUrl = process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000'
return NextResponse.json({
issuer: appUrl,
authorization_endpoint: `${appUrl}/api/mcp-oauth/authorize`,
token_endpoint: `${appUrl}/api/mcp-oauth/token`,
registration_endpoint: `${appUrl}/api/mcp-oauth/register`,
response_types_supported: ['code'],
grant_types_supported: ['authorization_code'],
code_challenge_methods_supported: ['S256'],
token_endpoint_auth_methods_supported: ['none', 'client_secret_post'],
scopes_supported: ['mcp'],
})
}
@@ -0,0 +1,15 @@
import { NextResponse } from 'next/server'
/**
* RFC 9728 — Protected Resource Metadata.
* Tells MCP clients which authorization server to use.
*/
export async function GET() {
const appUrl = process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000'
return NextResponse.json({
resource: `${appUrl}/api/extensions/ext/mcp-server/mcp`,
authorization_servers: [appUrl],
scopes_supported: ['mcp'],
})
}
+214
View File
@@ -0,0 +1,214 @@
import { createClient } from '@/lib/supabase/server'
import { NextResponse } from 'next/server'
import { createAuthCode } from '@/lib/auth/oauth-codes'
/**
* OAuth 2.0 Authorization Endpoint.
*
* GET → show consent page (or redirect to login)
* POST → process consent, create auth code, redirect to callback
*
* The API key is NOT created here — it's created in the token endpoint
* after PKCE verification, preventing orphaned keys on abandoned flows.
*/
// Known Claude callback URLs — reject all others to prevent open redirect
const ALLOWED_REDIRECT_PATTERNS = [
/^https:\/\/claude\.ai\/api\/mcp\/auth_callback$/,
/^https:\/\/claude\.com\/api\/mcp\/auth_callback$/,
/^http:\/\/localhost(:\d+)?\//, // Local development
/^http:\/\/127\.0\.0\.1(:\d+)?\//, // Local development
]
function isAllowedRedirectUri(uri: string): boolean {
return ALLOWED_REDIRECT_PATTERNS.some((pattern) => pattern.test(uri))
}
function buildLoginRedirect(request: Request): Response {
const url = new URL(request.url)
const next = `${url.pathname}${url.search}`
return NextResponse.redirect(
new URL(`/login?next=${encodeURIComponent(next)}`, url.origin)
)
}
function errorRedirect(redirectUri: string, state: string | null, error: string, desc: string): Response {
const url = new URL(redirectUri)
url.searchParams.set('error', error)
url.searchParams.set('error_description', desc)
if (state) url.searchParams.set('state', state)
return NextResponse.redirect(url.toString())
}
/**
* GET /api/mcp-oauth/authorize — show consent page
*/
export async function GET(request: Request) {
const url = new URL(request.url)
const redirectUri = url.searchParams.get('redirect_uri')
const state = url.searchParams.get('state')
const codeChallenge = url.searchParams.get('code_challenge')
const codeChallengeMethod = url.searchParams.get('code_challenge_method') || 'S256'
const responseType = url.searchParams.get('response_type')
if (responseType !== 'code') {
return NextResponse.json(
{ error: 'unsupported_response_type' },
{ status: 400 }
)
}
if (!redirectUri) {
return NextResponse.json(
{ error: 'invalid_request', error_description: 'redirect_uri is required' },
{ status: 400 }
)
}
// Validate redirect_uri against allowlist (prevents open redirect)
if (!isAllowedRedirectUri(redirectUri)) {
return NextResponse.json(
{ error: 'invalid_request', error_description: 'redirect_uri is not allowed' },
{ status: 400 }
)
}
if (codeChallengeMethod !== 'S256') {
return NextResponse.json(
{ error: 'invalid_request', error_description: 'Only S256 code_challenge_method is supported' },
{ status: 400 }
)
}
// Check if user is logged in
const supabase = await createClient()
const { data: { user } } = await supabase.auth.getUser()
if (!user) {
return buildLoginRedirect(request)
}
// Get company name for the consent page
const { data: settings } = await supabase
.from('company_settings')
.select('company_name')
.eq('user_id', user.id)
.single()
const companyName = settings?.company_name || user.email
// Render consent page
const html = `<!DOCTYPE html>
<html lang="sv">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="translate" content="no">
<title>Anslut MCP-klient — gnubok</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: system-ui, -apple-system, sans-serif; background: #fafafa; color: #111; display: flex; align-items: center; justify-content: center; min-height: 100vh; padding: 1rem; }
.card { background: white; border-radius: 12px; border: 1px solid #e5e5e5; padding: 2rem; max-width: 400px; width: 100%; }
h1 { font-size: 1.25rem; font-weight: 600; margin-bottom: 0.5rem; }
p { font-size: 0.875rem; color: #666; line-height: 1.5; margin-bottom: 1rem; }
.account { font-size: 0.875rem; color: #111; font-weight: 500; background: #f5f5f5; padding: 0.75rem 1rem; border-radius: 8px; margin-bottom: 1.5rem; }
.permissions { font-size: 0.8125rem; color: #444; margin-bottom: 1.5rem; }
.permissions li { margin-bottom: 0.25rem; }
.actions { display: flex; gap: 0.75rem; }
button { flex: 1; padding: 0.625rem 1rem; border-radius: 8px; font-size: 0.875rem; font-weight: 500; cursor: pointer; border: 1px solid #e5e5e5; }
.allow { background: #111; color: white; border-color: #111; }
.allow:hover { background: #333; }
.deny { background: white; color: #111; }
.deny:hover { background: #f5f5f5; }
</style>
</head>
<body>
<div class="card">
<h1>Anslut MCP-klient</h1>
<p>En extern applikation vill ansluta till ditt gnubok-konto.</p>
<div class="account">${escapeHtml(companyName)}</div>
<ul class="permissions">
<li>Visa och kategorisera transaktioner</li>
<li>Skapa och visa fakturor</li>
<li>Visa kunder och rapporter</li>
<li>Skapa verifikationer</li>
</ul>
<div class="actions">
<form method="POST" action="${url.pathname}${url.search}" style="flex:1;display:flex;">
<input type="hidden" name="consent" value="deny">
<button type="submit" class="deny" style="width:100%;">Neka</button>
</form>
<form method="POST" action="${url.pathname}${url.search}" style="flex:1;display:flex;">
<input type="hidden" name="consent" value="allow">
<button type="submit" class="allow" style="width:100%;">Tillåt</button>
</form>
</div>
</div>
</body>
</html>`
return new Response(html, {
headers: { 'Content-Type': 'text/html; charset=utf-8' },
})
}
/**
* POST /api/mcp-oauth/authorize — process consent, issue auth code
*/
export async function POST(request: Request) {
const url = new URL(request.url)
const redirectUri = url.searchParams.get('redirect_uri')
const state = url.searchParams.get('state')
const codeChallenge = url.searchParams.get('code_challenge') || ''
const codeChallengeMethod = url.searchParams.get('code_challenge_method') || 'S256'
if (!redirectUri) {
return NextResponse.json({ error: 'invalid_request' }, { status: 400 })
}
if (!isAllowedRedirectUri(redirectUri)) {
return NextResponse.json(
{ error: 'invalid_request', error_description: 'redirect_uri is not allowed' },
{ status: 400 }
)
}
// Check auth
const supabase = await createClient()
const { data: { user } } = await supabase.auth.getUser()
if (!user) {
return buildLoginRedirect(request)
}
// Parse form body
const formData = await request.formData()
const consent = formData.get('consent')
if (consent !== 'allow') {
return errorRedirect(redirectUri, state, 'access_denied', 'User denied the request')
}
// Create auth code with userId (NO API key — that's created at /token after PKCE)
const code = createAuthCode({
userId: user.id,
codeChallenge,
codeChallengeMethod,
redirectUri,
})
// Redirect to callback with the code
const callbackUrl = new URL(redirectUri)
callbackUrl.searchParams.set('code', code)
if (state) callbackUrl.searchParams.set('state', state)
return NextResponse.redirect(callbackUrl.toString())
}
function escapeHtml(str: string): string {
return str
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
}
+27
View File
@@ -0,0 +1,27 @@
import { NextResponse } from 'next/server'
import crypto from 'crypto'
/**
* RFC 7591 — Dynamic Client Registration.
* Claude Desktop registers itself as an OAuth client before starting the auth flow.
* We accept any registration and return a client_id.
*/
export async function POST(request: Request) {
let body: Record<string, unknown>
try {
body = await request.json()
} catch {
return NextResponse.json({ error: 'invalid_request' }, { status: 400 })
}
const clientId = crypto.randomUUID()
return NextResponse.json({
client_id: clientId,
client_name: (body.client_name as string) || 'MCP Client',
redirect_uris: body.redirect_uris || [],
grant_types: ['authorization_code'],
response_types: ['code'],
token_endpoint_auth_method: 'none',
}, { status: 201 })
}
+128
View File
@@ -0,0 +1,128 @@
import { NextResponse } from 'next/server'
import { decryptAuthCode, verifyPkce, hashAuthCode } from '@/lib/auth/oauth-codes'
import { generateApiKey } from '@/lib/auth/api-keys'
import { createServiceClientNoCookies } from '@/lib/auth/api-keys'
/**
* OAuth 2.0 Token Endpoint.
*
* Exchanges an authorization code for an API key (access token).
* 1. Decrypts the stateless auth code
* 2. Checks for replay (single-use enforcement per OAuth 2.1 §4.1.2)
* 3. Verifies PKCE (S256 only)
* 4. Creates the API key (deferred from /authorize to prevent orphaned keys)
* 5. Returns the key as a bearer token
*/
export async function POST(request: Request) {
let params: URLSearchParams
const contentType = request.headers.get('content-type') || ''
if (contentType.includes('application/x-www-form-urlencoded')) {
const text = await request.text()
params = new URLSearchParams(text)
} else if (contentType.includes('application/json')) {
const json = await request.json()
params = new URLSearchParams(json as Record<string, string>)
} else {
return NextResponse.json({ error: 'unsupported_content_type' }, { status: 400 })
}
const grantType = params.get('grant_type')
const code = params.get('code')
const codeVerifier = params.get('code_verifier')
const redirectUri = params.get('redirect_uri')
if (grantType !== 'authorization_code') {
return NextResponse.json(
{ error: 'unsupported_grant_type', error_description: 'Only authorization_code is supported' },
{ status: 400 }
)
}
if (!code) {
return NextResponse.json(
{ error: 'invalid_request', error_description: 'Missing code parameter' },
{ status: 400 }
)
}
// Decrypt the auth code
const payload = decryptAuthCode(code)
if (!payload) {
return NextResponse.json(
{ error: 'invalid_grant', error_description: 'Invalid or expired authorization code' },
{ status: 400 }
)
}
// Verify redirect_uri matches
if (redirectUri && redirectUri !== payload.redirectUri) {
return NextResponse.json(
{ error: 'invalid_grant', error_description: 'redirect_uri mismatch' },
{ status: 400 }
)
}
// Verify PKCE (S256 only)
if (!codeVerifier) {
return NextResponse.json(
{ error: 'invalid_request', error_description: 'code_verifier is required' },
{ status: 400 }
)
}
if (!verifyPkce(codeVerifier, payload.codeChallenge)) {
return NextResponse.json(
{ error: 'invalid_grant', error_description: 'PKCE verification failed' },
{ status: 400 }
)
}
// Single-use enforcement: check and mark code as used (atomically via unique constraint)
const codeHash = hashAuthCode(code)
const supabase = createServiceClientNoCookies()
const { error: replayError } = await supabase
.from('oauth_used_codes')
.insert({ code_hash: codeHash })
if (replayError) {
// Unique constraint violation = code already used
return NextResponse.json(
{ error: 'invalid_grant', error_description: 'Authorization code already used' },
{ status: 400 }
)
}
// Clean up expired codes (non-blocking, best-effort)
supabase
.from('oauth_used_codes')
.delete()
.lt('created_at', new Date(Date.now() - 10 * 60 * 1000).toISOString())
.then(() => {})
// Create the API key now (after PKCE verification — prevents orphaned keys)
const { key, hash, prefix } = generateApiKey()
const { error: insertError } = await supabase
.from('api_keys')
.insert({
user_id: payload.userId,
key_hash: hash,
key_prefix: prefix,
name: 'MCP-klient (OAuth)',
})
if (insertError) {
return NextResponse.json(
{ error: 'server_error', error_description: 'Failed to create API key' },
{ status: 500 }
)
}
return NextResponse.json({
access_token: key,
token_type: 'Bearer',
scope: 'mcp',
})
}
+107
View File
@@ -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 })
}
+31
View File
@@ -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 })
}
+89
View File
@@ -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
},
})
}
+2
View File
@@ -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' },
+69
View File
@@ -0,0 +1,69 @@
'use client'
import { Card, CardContent } from '@/components/ui/card'
import { formatCurrency } from '@/lib/utils'
import type { KPIReport } from '@/types'
interface KPIHeroCardsProps {
report: KPIReport
}
export function KPIHeroCards({ report }: KPIHeroCardsProps) {
return (
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
{/* Gross margin */}
<Card>
<CardContent className="p-5">
<p className="text-xs text-muted-foreground mb-1">Bruttomarginal</p>
<p className="font-display text-xl tabular-nums tracking-tight">
{report.grossMargin !== null ? `${report.grossMargin}%` : '—'}
</p>
<p className="text-xs text-muted-foreground mt-1">av intäkter</p>
</CardContent>
</Card>
{/* Net result */}
<Card>
<CardContent className="p-5">
<p className="text-xs text-muted-foreground mb-1">Resultat</p>
<p className={`font-display text-xl tabular-nums tracking-tight ${
report.netResult >= 0 ? 'text-[hsl(var(--chart-1))]' : 'text-[hsl(var(--chart-2))]'
}`}>
{formatCurrency(report.netResult)}
</p>
<p className="text-xs text-muted-foreground mt-1">netto</p>
</CardContent>
</Card>
{/* Cash position */}
<Card>
<CardContent className="p-5">
<p className="text-xs text-muted-foreground mb-1">Kassa</p>
<p className={`font-display text-xl tabular-nums tracking-tight ${
report.cashPosition > 0 ? 'text-[hsl(var(--chart-1))]' : 'text-[hsl(var(--chart-2))]'
}`}>
{formatCurrency(report.cashPosition)}
</p>
<p className="text-xs text-muted-foreground mt-1">likvida medel</p>
</CardContent>
</Card>
{/* Outstanding receivables */}
<Card>
<CardContent className="p-5">
<p className="text-xs text-muted-foreground mb-1">Kundfordringar</p>
<p className="font-display text-xl tabular-nums tracking-tight">
{formatCurrency(report.outstandingReceivables)}
</p>
{report.overdueReceivables > 0 ? (
<p className="text-xs text-[hsl(var(--chart-2))] mt-1">
varav förfallet: {formatCurrency(report.overdueReceivables)}
</p>
) : (
<p className="text-xs text-muted-foreground mt-1">utestående</p>
)}
</CardContent>
</Card>
</div>
)
}
+99
View File
@@ -0,0 +1,99 @@
'use client'
import { Card, CardContent } from '@/components/ui/card'
import { TrendingUp, TrendingDown, Info } from 'lucide-react'
import { formatCurrency } from '@/lib/utils'
import type { KPIReport } from '@/types'
interface KPIOperationalGridProps {
report: KPIReport
}
export function KPIOperationalGrid({ report }: KPIOperationalGridProps) {
return (
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
{/* Revenue growth */}
<Card>
<CardContent className="p-5">
<p className="text-xs text-muted-foreground mb-1">Intäktstillväxt</p>
{!report.periodComplete ? (
<p className="text-sm text-muted-foreground">Välj ett avslutat räkenskapsår</p>
) : report.revenueGrowth !== null ? (
<div className="flex items-center gap-2">
{report.revenueGrowth >= 0 ? (
<TrendingUp className="h-4 w-4 text-[hsl(var(--chart-1))]" />
) : (
<TrendingDown className="h-4 w-4 text-[hsl(var(--chart-2))]" />
)}
<p className={`font-display text-xl tabular-nums tracking-tight ${
report.revenueGrowth >= 0 ? 'text-[hsl(var(--chart-1))]' : 'text-[hsl(var(--chart-2))]'
}`}>
{report.revenueGrowth > 0 ? '+' : ''}{report.revenueGrowth}%
</p>
</div>
) : (
<p className="text-sm text-muted-foreground">Första räkenskapsåret</p>
)}
</CardContent>
</Card>
{/* Expense ratio */}
<Card>
<CardContent className="p-5">
<p className="text-xs text-muted-foreground mb-1">Kostnadsandel</p>
{report.expenseRatio !== null ? (
<>
<p className="font-display text-xl tabular-nums tracking-tight">
{report.expenseRatio}%
</p>
<div className="mt-2 h-1.5 rounded-full bg-muted overflow-hidden">
<div
className="h-full rounded-full bg-[hsl(var(--chart-2))]/60 transition-all"
style={{ width: `${Math.min(report.expenseRatio, 100)}%` }}
/>
</div>
</>
) : (
<p className="text-sm text-muted-foreground">Inga intäkter</p>
)}
</CardContent>
</Card>
{/* Avg payment days */}
<Card>
<CardContent className="p-5">
<div className="flex items-center gap-1.5 mb-1">
<p className="text-xs text-muted-foreground">Snittbetaltid</p>
{report.avgPaymentDays === null && (
<span title="Kräver minst 5 betalda fakturor med betalningsdatum. Sätts via fakturering i gnubok eller bankmatchning.">
<Info className="h-3 w-3 text-muted-foreground/60" />
</span>
)}
</div>
{report.avgPaymentDays !== null ? (
<p className="font-display text-xl tabular-nums tracking-tight">
{report.avgPaymentDays} <span className="text-sm font-normal text-muted-foreground">dagar</span>
</p>
) : (
<p className="text-sm text-muted-foreground">Inte tillräckligt med data</p>
)}
</CardContent>
</Card>
{/* VAT liability */}
<Card>
<CardContent className="p-5">
<p className="text-xs text-muted-foreground mb-1">Momsskuld</p>
<p className={`font-display text-xl tabular-nums tracking-tight ${
report.vatLiability > 0 ? 'text-[hsl(var(--chart-2))]' : 'text-[hsl(var(--chart-1))]'
}`}>
{formatCurrency(Math.abs(report.vatLiability))}
</p>
<p className="text-xs text-muted-foreground mt-1">
{report.vatLiability > 0 ? 'Att betala' : report.vatLiability < 0 ? 'Att återfå' : 'Jämnt'}
</p>
</CardContent>
</Card>
</div>
)
}
+96
View File
@@ -0,0 +1,96 @@
'use client'
import {
Area,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
ResponsiveContainer,
Legend,
Line,
ComposedChart,
} from 'recharts'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { formatCurrency } from '@/lib/utils'
interface KPITrendChartProps {
months: { label: string; income: number; expenses: number; net: number }[]
}
export function KPITrendChart({ months }: KPITrendChartProps) {
if (months.length === 0) return null
return (
<Card>
<CardHeader className="pb-2">
<CardTitle className="text-base">Intäkter, kostnader & resultat per månad</CardTitle>
</CardHeader>
<CardContent>
<ResponsiveContainer width="100%" height={300}>
<ComposedChart
data={months}
margin={{ top: 5, right: 10, left: 10, bottom: 5 }}
>
<CartesianGrid strokeDasharray="3 3" vertical={false} />
<XAxis dataKey="label" tick={{ fontSize: 12 }} />
<YAxis
tickFormatter={(v) =>
new Intl.NumberFormat('sv-SE', { notation: 'compact' }).format(v)
}
tick={{ fontSize: 11 }}
/>
<Tooltip
formatter={(value, name) => [
formatCurrency(Number(value)),
name === 'income'
? 'Intäkter'
: name === 'expenses'
? 'Kostnader'
: 'Resultat',
]}
contentStyle={{
fontSize: '12px',
borderRadius: '8px',
border: '1px solid hsl(var(--border))',
backgroundColor: 'hsl(var(--card))',
}}
/>
<Legend
formatter={(value: string) =>
value === 'income'
? 'Intäkter'
: value === 'expenses'
? 'Kostnader'
: 'Resultat'
}
/>
<Area
type="monotone"
dataKey="income"
fill="hsl(var(--chart-1))"
fillOpacity={0.15}
stroke="hsl(var(--chart-1))"
strokeWidth={1.5}
/>
<Area
type="monotone"
dataKey="expenses"
fill="hsl(var(--chart-2))"
fillOpacity={0.15}
stroke="hsl(var(--chart-2))"
strokeWidth={1.5}
/>
<Line
type="monotone"
dataKey="net"
stroke="hsl(var(--chart-3))"
strokeWidth={2}
dot={false}
/>
</ComposedChart>
</ResponsiveContainer>
</CardContent>
</Card>
)
}
+305
View File
@@ -0,0 +1,305 @@
'use client'
import { useState, useEffect, useCallback } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import { useToast } from '@/components/ui/use-toast'
import { Loader2, Plus, Copy, Check, Trash2, Key } from 'lucide-react'
interface ApiKey {
id: string
key_prefix: string
name: string
scopes: string[] | null
rate_limit_rpm: number
last_used_at: string | null
revoked_at: string | null
created_at: string
}
export function ApiKeysPanel() {
const { toast } = useToast()
const [keys, setKeys] = useState<ApiKey[]>([])
const [isLoading, setIsLoading] = useState(true)
const [isCreating, setIsCreating] = useState(false)
const [showCreateDialog, setShowCreateDialog] = useState(false)
const [showKeyDialog, setShowKeyDialog] = useState(false)
const [newKeyName, setNewKeyName] = useState('')
const [newKeyValue, setNewKeyValue] = useState('')
const [copied, setCopied] = useState(false)
const [revokingId, setRevokingId] = useState<string | null>(null)
const fetchKeys = useCallback(async () => {
try {
const res = await fetch('/api/settings/api-keys')
const json = await res.json()
if (json.data) {
setKeys(json.data.filter((k: ApiKey) => !k.revoked_at))
}
} catch {
toast({ title: 'Fel', description: 'Kunde inte hämta API-nycklar', variant: 'destructive' })
} finally {
setIsLoading(false)
}
}, [toast])
useEffect(() => {
fetchKeys()
}, [fetchKeys])
async function handleCreate() {
setIsCreating(true)
try {
const res = await fetch('/api/settings/api-keys', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: newKeyName || 'MCP-nyckel' }),
})
const json = await res.json()
if (!res.ok) {
toast({ title: 'Fel', description: json.error, variant: 'destructive' })
return
}
setNewKeyValue(json.data.key)
setShowCreateDialog(false)
setShowKeyDialog(true)
setNewKeyName('')
fetchKeys()
} catch {
toast({ title: 'Fel', description: 'Kunde inte skapa nyckel', variant: 'destructive' })
} finally {
setIsCreating(false)
}
}
async function handleRevoke(id: string) {
setRevokingId(id)
try {
await fetch(`/api/settings/api-keys/${id}`, { method: 'DELETE' })
setKeys((prev) => prev.filter((k) => k.id !== id))
toast({ title: 'Nyckel återkallad' })
} catch {
toast({ title: 'Fel', description: 'Kunde inte återkalla nyckel', variant: 'destructive' })
} finally {
setRevokingId(null)
}
}
function handleCopy() {
navigator.clipboard.writeText(newKeyValue)
setCopied(true)
setTimeout(() => setCopied(false), 2000)
}
function formatDate(iso: string | null) {
if (!iso) return '—'
return new Date(iso).toLocaleDateString('sv-SE', {
year: 'numeric',
month: 'short',
day: 'numeric',
})
}
const mcpUrl = typeof window !== 'undefined'
? `${window.location.origin}/api/extensions/ext/mcp-server/mcp`
: '/api/extensions/ext/mcp-server/mcp'
return (
<div className="space-y-6">
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<div>
<CardTitle>API-nycklar</CardTitle>
<CardDescription>
Hantera nycklar för MCP-klienter (Claude, Cursor) och andra integrationer.
</CardDescription>
</div>
<Button
size="sm"
onClick={() => setShowCreateDialog(true)}
disabled={keys.length >= 10}
>
<Plus className="mr-1.5 h-3.5 w-3.5" />
Skapa nyckel
</Button>
</div>
</CardHeader>
<CardContent>
{isLoading ? (
<div className="flex items-center justify-center py-8">
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
</div>
) : keys.length === 0 ? (
<div className="flex flex-col items-center justify-center py-8 text-center">
<Key className="h-8 w-8 text-muted-foreground/50 mb-3" />
<p className="text-sm text-muted-foreground">Inga API-nycklar ännu.</p>
<p className="text-xs text-muted-foreground mt-1">
Skapa en nyckel för att koppla din MCP-klient.
</p>
</div>
) : (
<div className="space-y-3">
{keys.map((key) => (
<div
key={key.id}
className="flex items-center justify-between rounded-md border px-4 py-3"
>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<p className="text-sm font-medium truncate">{key.name}</p>
</div>
<div className="flex items-center gap-3 mt-1">
<code className="text-xs text-muted-foreground font-mono">
{key.key_prefix}...
</code>
<span className="text-xs text-muted-foreground">
Skapad {formatDate(key.created_at)}
</span>
<span className="text-xs text-muted-foreground">
{key.last_used_at
? `Använd ${formatDate(key.last_used_at)}`
: 'Aldrig använd'}
</span>
</div>
</div>
<Button
variant="ghost"
size="sm"
onClick={() => handleRevoke(key.id)}
disabled={revokingId === key.id}
className="text-destructive hover:text-destructive"
>
{revokingId === key.id ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<Trash2 className="h-3.5 w-3.5" />
)}
</Button>
</div>
))}
</div>
)}
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="text-base">Anslut MCP-klient</CardTitle>
</CardHeader>
<CardContent className="space-y-6">
<div>
<p className="text-sm font-medium mb-1">Claude Desktop</p>
<p className="text-xs text-muted-foreground mb-2">
Inställningar &rarr; Connectors &rarr; Add custom connector. Klistra in URL:en nedan.
Du loggas in automatiskt via OAuth.
</p>
<pre className="rounded-md bg-muted p-3 text-xs font-mono overflow-x-auto select-all">
{mcpUrl}
</pre>
</div>
<div>
<p className="text-sm font-medium mb-1">Claude Code / Cursor</p>
<p className="text-xs text-muted-foreground mb-2">
Kör i terminalen med en API-nyckel:
</p>
<pre className="rounded-md bg-muted p-4 text-xs font-mono overflow-x-auto">
{`claude mcp add gnubok --transport http \\
--url ${mcpUrl} \\
--header "Authorization: Bearer gnubok_sk_..."`}
</pre>
</div>
</CardContent>
</Card>
{/* Create key dialog */}
<Dialog open={showCreateDialog} onOpenChange={setShowCreateDialog}>
<DialogContent>
<DialogHeader>
<DialogTitle>Skapa API-nyckel</DialogTitle>
<DialogDescription>
Ge nyckeln ett namn så du vet vad den används till.
</DialogDescription>
</DialogHeader>
<div className="space-y-3">
<Label htmlFor="key-name">Namn</Label>
<Input
id="key-name"
placeholder="t.ex. Claude Desktop"
value={newKeyName}
onChange={(e) => setNewKeyName(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && handleCreate()}
/>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setShowCreateDialog(false)}>
Avbryt
</Button>
<Button onClick={handleCreate} disabled={isCreating}>
{isCreating && <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />}
Skapa
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* Show key once dialog */}
<Dialog open={showKeyDialog} onOpenChange={(open) => {
if (!open) {
setNewKeyValue('')
setCopied(false)
}
setShowKeyDialog(open)
}}>
<DialogContent>
<DialogHeader>
<DialogTitle>Din nya API-nyckel</DialogTitle>
<DialogDescription>
Kopiera nyckeln nu. Den visas bara en gång.
</DialogDescription>
</DialogHeader>
<div className="relative">
<code className="block rounded-md bg-muted p-4 pr-12 text-sm font-mono break-all">
{newKeyValue}
</code>
<Button
variant="ghost"
size="sm"
className="absolute right-2 top-2"
onClick={handleCopy}
>
{copied ? (
<Check className="h-4 w-4 text-green-600" />
) : (
<Copy className="h-4 w-4" />
)}
</Button>
</div>
<DialogFooter>
<Button onClick={() => {
setShowKeyDialog(false)
setNewKeyValue('')
setCopied(false)
}}>
Klar
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
)
}
+1 -1
View File
@@ -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"]}
+2 -1
View File
@@ -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."
+45
View File
@@ -0,0 +1,45 @@
import type { Extension } from '@/lib/extensions/types'
import { handleMcpRequest } from './server'
export const mcpServerExtension: Extension = {
id: 'mcp-server',
name: 'MCP Server',
version: '1.0.0',
settingsPanel: {
label: 'MCP-server (API)',
path: '/settings?tab=api',
},
apiRoutes: [
{
method: 'POST',
path: '/mcp',
skipAuth: true, // Auth handled via API key in the handler
handler: handleMcpRequest,
},
// MCP Streamable HTTP also needs GET for SSE and DELETE for session termination
{
method: 'GET',
path: '/mcp',
skipAuth: true,
handler: async () => {
const appUrl = process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000'
return new Response('Authorization required', {
status: 401,
headers: {
'WWW-Authenticate': `Bearer resource_metadata="${appUrl}/.well-known/oauth-protected-resource"`,
},
})
},
},
{
method: 'DELETE',
path: '/mcp',
skipAuth: true,
handler: async () => new Response(null, { status: 204 }), // Stateless — no sessions to terminate
},
],
eventHandlers: [],
}
@@ -0,0 +1,18 @@
{
"id": "mcp-server",
"sector": "general",
"exportName": "mcpServerExtension",
"entryPoint": "@/extensions/general/mcp-server",
"requiredEnvVars": [],
"optionalEnvVars": [],
"npmDependencies": [],
"definition": {
"name": "MCP-server (API)",
"category": "operations",
"icon": "Terminal",
"dataPattern": "manual",
"hasOwnData": false,
"description": "Gör bokföring via Claude, Cursor eller annan MCP-klient",
"longDescription": "Exponerar gnuboks bokföringsmotor som MCP-verktyg (Model Context Protocol). Koppla din MCP-klient med en API-nyckel och gör bokföring genom konversation: visa okategoriserade transaktioner, bokför dem, skapa fakturor."
}
}
File diff suppressed because it is too large Load Diff
+65
View File
@@ -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 }
}

Some files were not shown because too many files have changed in this diff Show More