* fix: prevent Chrome auto-translate from crashing React during onboarding
Chrome auto-translate modifies DOM text nodes when it detects a Swedish
page (lang="sv") in a browser set to English. React does not expect
external DOM mutations and throws, crashing the entire component tree
into global-error.tsx on every step transition.
Add translate="no" and <meta name="google" content="notranslate"> to
suppress browser translation. Also fix timezone-unsafe date parsing in
fiscal period validation (new Date("YYYY-MM-DD") + getDate() returns
local-timezone values, shifting dates by -1 day in Western timezones).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: add notranslate meta tag to global-error.tsx for consistency
Per review feedback — global-error.tsx renders its own <html> document,
so it needs the same <meta name="google" content="notranslate"> tag as
layout.tsx to fully suppress Chrome translation on error pages.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat: add MCP server extension with OAuth, API keys, and KPI dashboard
Let users do bookkeeping through Claude Desktop, Claude Code, or any
MCP-compatible client. "Show my uncategorized transactions." "Book that
as office supplies." "Invoice Acme for 15,000 kr."
MCP server (extension):
- 10 tools: transactions, categorization, customers, invoices,
trial balance, VAT report, KPI report, income statement
- JSON-RPC 2.0 protocol (no SDK dependency, works in serverless)
- Tool annotations, pagination, input validation per MCP best practices
- Same engine as web UI (VAT rules, exchange rates, event emission)
API key infrastructure (core):
- api_keys table with RLS, rate limiting (100 RPM), scopes column
- Atomic rate limit via DB RPC (validate_and_increment_api_key)
- Key management API routes + settings UI panel
OAuth 2.1 for Claude Desktop connectors:
- .well-known/oauth-protected-resource + oauth-authorization-server
- Authorization endpoint with consent page
- Token endpoint with PKCE verification
- Stateless encrypted auth codes (AES-256-GCM, no DB storage)
- Dynamic client registration
KPI dashboard:
- /nyckeltal page with hero cards, operational grid, trend chart
- GET /api/reports/kpi endpoint
- Gross margin, cash position, expense ratio, avg payment days,
VAT liability, revenue/expense trend
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: address OAuth security vulnerabilities from code review
Critical fixes:
- Auth code replay: Track used codes in oauth_used_codes table with
unique constraint. Codes are single-use per OAuth 2.1 §4.1.2.
- Open redirect: Validate redirect_uri against hardcoded allowlist
of known Claude callback URLs + localhost for dev.
P1 fixes:
- Move API key creation from /authorize to /token endpoint. Keys are
only created after PKCE verification, preventing orphaned keys on
abandoned OAuth flows.
- Add ensureInitialized() to MCP server so event handlers load and
transaction.categorized events reach extensions.
P2 fixes:
- Remove 'plain' from PKCE methods — only S256 is advertised and
accepted.
- Fix extension count in sectors test (10 → 11 for mcp-server).
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix: remove duplicate ensureInitialized() that caused circular import
The extension router (ext/[...path]/route.ts) already calls
ensureInitialized() before dispatching to handlers. The duplicate
call in server.ts created a circular import that Turbopack couldn't
resolve, breaking the Vercel build.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
152 lines
4.8 KiB
Python
152 lines
4.8 KiB
Python
"""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'")
|