Skip to content

Open-source personal finance manager. Self-hosted, privacy-first.

feat: expose built-in MCP server to external agents (closes #223) (#224)

Tássio Noronha4d0fb14bfbfa
diff --git a/.gitignore b/.gitignore
index 3864bbb0..c54e80f2 100644
--- a/.gitignore
+++ b/.gitignore
@@ -3,6 +3,7 @@
.DS_Store
.playwright-mcp/
.claude
+.mcp.json
docs/plans/
tmp/
docker-compose.override.yml
diff --git a/backend/app/agents/api/info.py b/backend/app/agents/api/info.py
index 40e29efa..e0272696 100644
--- a/backend/app/agents/api/info.py
+++ b/backend/app/agents/api/info.py
@@ -18,4 +18,5 @@ async def get_agents_info():
"default_top_n": s.default_top_n,
"default_similarity_threshold": s.default_similarity_threshold,
"extra_mcp_servers_configured": bool(s.extra_mcp_servers.strip()),
+ "mcp_external_ttl_days": s.mcp_external_ttl_days,
}
diff --git a/backend/app/agents/api/mcp_tokens.py b/backend/app/agents/api/mcp_tokens.py
new file mode 100644
index 00000000..83374153
--- /dev/null
+++ b/backend/app/agents/api/mcp_tokens.py
@@ -0,0 +1,34 @@
+"""Mint long-lived MCP tokens for external agents.
+
+Lets a logged-in user generate a JWT they can paste into Claude Desktop,
+n8n, or any other MCP client. The token is signed with the same
+`AGENTS_MCP_JWT_SECRET` the internal runtime uses, scoped to the calling
+user, with a configurable TTL (default 90 days) and an `ext: true`
+claim. The MCP server already verifies any valid JWT — no auth changes
+needed there.
+
+Follows the AGENTS_ENABLED master switch: when agents are off, the
+router isn't mounted at all so the endpoint 404s.
+"""
+from __future__ import annotations
+
+from fastapi import APIRouter, Depends, status
+
+from app.agents.config import get_agent_settings
+from app.agents.mcp.auth import mint_token
+from app.core.auth import current_active_user
+from app.models.user import User
+
+router = APIRouter(prefix="/api/agents/mcp-tokens", tags=["agents"])
+
+
[email protected]("", status_code=status.HTTP_201_CREATED)
+async def create_mcp_token(user: User = Depends(current_active_user)):
+ s = get_agent_settings()
+ ttl_seconds = max(s.mcp_external_ttl_days, 1) * 86400
+ token = mint_token(user_id=user.id, ttl_seconds=ttl_seconds, external=True)
+ return {
+ "token": token,
+ "expires_in_seconds": ttl_seconds,
+ "expires_in_days": s.mcp_external_ttl_days,
+ }
diff --git a/backend/app/agents/config.py b/backend/app/agents/config.py
index 5c227d0f..cab92525 100644
--- a/backend/app/agents/config.py
+++ b/backend/app/agents/config.py
@@ -20,6 +20,12 @@ class AgentSettings(BaseSettings):
mcp_jwt_secret: str = "change-me-in-production"
mcp_jwt_ttl_seconds: int = 600
+ # TTL for long-lived tokens minted via the UI for external agents
+ # (Claude Desktop, n8n, custom clients). The feature itself follows
+ # `enabled` — if agents are on, the mint endpoint is mounted and the
+ # mcp-server container publishes port 8765.
+ mcp_external_ttl_days: int = 90
+
# Embedding dimension for the knowledge_chunks vector column. Locked at
# migration time. 1536 covers OpenAI text-embedding-3-small (default) and
# nomic-embed-text via Matryoshka padding/truncation.
diff --git a/backend/app/agents/mcp/auth.py b/backend/app/agents/mcp/auth.py
index 368d99ef..55bdc3f0 100644
--- a/backend/app/agents/mcp/auth.py
+++ b/backend/app/agents/mcp/auth.py
@@ -20,6 +20,7 @@ def mint_token(
conversation_id: Optional[uuid.UUID] = None,
agent_id: Optional[uuid.UUID] = None,
ttl_seconds: Optional[int] = None,
+ external: bool = False,
) -> str:
s = get_agent_settings()
now = int(time.time())
@@ -34,4 +35,6 @@ def mint_token(
payload["conv_id"] = str(conversation_id)
if agent_id:
payload["agent_id"] = str(agent_id)
+ if external:
+ payload["ext"] = True
return jwt.encode(payload, s.mcp_jwt_secret, algorithm=JWT_ALGO)
diff --git a/backend/app/main.py b/backend/app/main.py
index 6c3b2ffa..8eb1077d 100644
--- a/backend/app/main.py
+++ b/backend/app/main.py
@@ -148,13 +148,15 @@ if os.getenv("AGENTS_ENABLED", "false").strip().lower() in ("1", "true", "yes",
from app.agents.api.conversations import router as agents_conversations_router
from app.agents.api.chat import router as agents_chat_router
from app.agents.api.knowledge import router as agents_knowledge_router
+ from app.agents.api.mcp_tokens import router as agents_mcp_tokens_router
- # Mount literal-prefix routers (conversations, connections) BEFORE
- # the generic agents router so paths like /api/agents/connections
- # don't get captured by /api/agents/{agent_id}.
+ # Mount literal-prefix routers (conversations, connections,
+ # mcp-tokens) BEFORE the generic agents router so paths like
+ # /api/agents/connections don't get captured by /api/agents/{agent_id}.
app.include_router(agents_info_router)
app.include_router(agents_connections_router)
app.include_router(agents_conversations_router)
+ app.include_router(agents_mcp_tokens_router)
app.include_router(agents_router)
app.include_router(agents_chat_router)
app.include_router(agents_knowledge_router)
diff --git a/backend/mcp_server/auth.py b/backend/mcp_server/auth.py
index 750c3c4f..1dde4b14 100644
--- a/backend/mcp_server/auth.py
+++ b/backend/mcp_server/auth.py
@@ -26,6 +26,10 @@ class CallContext:
user_id: uuid.UUID
conversation_id: Optional[uuid.UUID] = None
agent_id: Optional[uuid.UUID] = None
+ # True when the JWT was minted for an external agent (Claude Desktop,
+ # n8n, etc.) rather than Securo's own runtime. Used for log tagging;
+ # tool authorization is identical (same user scope).
+ external: bool = False
def _settings():
@@ -62,4 +66,5 @@ def verify_request(request: Request) -> CallContext:
user_id=user_id,
conversation_id=uuid.UUID(conv_raw) if conv_raw else None,
agent_id=uuid.UUID(agent_raw) if agent_raw else None,
+ external=bool(payload.get("ext")),
)
diff --git a/backend/mcp_server/tools/proposals.py b/backend/mcp_server/tools/proposals.py
index 3f6b1dde..7092f66a 100644
--- a/backend/mcp_server/tools/proposals.py
+++ b/backend/mcp_server/tools/proposals.py
@@ -1,13 +1,21 @@
"""Propose-mutations.
-These tools NEVER write to the DB. They return a structured proposal that
-the agent surfaces to the user. The user confirms in the UI, which calls
-the existing Securo write endpoint to do the real change. Keeps MCP safe
-and gives the user a chance to review.
+In Securo's own runtime these tools NEVER write to the DB. They return a
+structured proposal that the agent surfaces to the user. The user confirms
+in the UI, which calls the existing Securo write endpoint to do the real
+change. Keeps MCP safe and gives the user a chance to review.
+
+When called via an *external* token (Claude Desktop, n8n, custom clients
+— `ctx.external` is true), there is no Apply button to render. In that
+case the tools accept an extra `apply: true` flag: first call returns
+the preview as usual; a follow-up call with `apply=true` performs the
+write directly. Internal callers never set `apply`, so behavior is
+unchanged for Securo's own UI.
"""
from __future__ import annotations
from datetime import date
+from decimal import Decimal
from typing import Any
from sqlalchemy import select
@@ -18,6 +26,24 @@ from app.models.category import Category
from app.models.group import Group, GroupMember
from app.models.recurring_transaction import RecurringTransaction
from app.models.transaction import Transaction
+from app.schemas.budget import BudgetCreate
+from app.schemas.category import CategoryCreate
+from app.schemas.goal import GoalCreate
+from app.schemas.recurring_transaction import (
+ RecurringTransactionCreate,
+ RecurringTransactionUpdate,
+)
+from app.schemas.rule import RuleAction, RuleCondition, RuleCreate
+from app.schemas.transaction import TransactionCreate
+from app.schemas.transaction_split import TransactionSplitInput, TransactionSplitsInput
+from app.services import (
+ budget_service,
+ category_service,
+ goal_service,
+ recurring_transaction_service,
+ rule_service,
+ transaction_service,
+)
from mcp_server.auth import CallContext
from mcp_server.registry import tool
from mcp_server.tools._helpers import num, parse_date, parse_uuid, parse_uuid_list
@@ -27,15 +53,36 @@ from mcp_server.tools._helpers import num, parse_date, parse_uuid, parse_uuid_li
# deciding when to use a tool AND when describing the result to the user.
# The strong "REQUIRES USER CONFIRMATION" framing prevents the model from
# saying "Pronto! Criei…" / "Done! I added…" — the action is NOT executed
-# by the tool call; it only takes effect when the user clicks Apply.
+# by the tool call; it only takes effect when the user clicks Apply (or
+# the caller re-invokes with apply=true on the external transport).
_PROPOSAL_PREFACE = (
- "[PROPOSAL — PREVIEW ONLY, NOT EXECUTED. The user MUST click Apply in "
- "the UI to confirm. Describe results as 'I prepared a proposal…' or "
- "'Here's a preview…' — NEVER as 'I created' / 'Done' / 'Ready'. The "
- "Apply button + diff card render automatically; do not duplicate the "
- "details in your reply.] "
+ "[PROPOSAL — PREVIEW ONLY, NOT EXECUTED. The user MUST confirm before "
+ "the change happens. In Securo's UI an Apply button + diff card render "
+ "automatically — do not duplicate the details in your reply. When you "
+ "are running through an external MCP client (no Apply button in chat), "
+ "pass apply=true on a follow-up call AFTER the user explicitly "
+ "confirms in the conversation. Never set apply=true on the first call. "
+ "Describe results as 'I prepared a proposal…' / 'Here's a preview…' — "
+ "NEVER as 'I created' / 'Done' / 'Ready' unless the response includes "
+ "applied=true.] "
)
+# Apply flag, attached to every propose_* tool's parameters. Default false.
+_APPLY_FIELD = {
+ "type": "boolean",
+ "default": False,
+ "description": (
+ "External clients only. When true (and the call is authenticated "
+ "with an external MCP token), executes the change instead of "
+ "returning a preview. Ignored by Securo's internal runtime."
+ ),
+}
+
+
+def _can_apply(ctx: CallContext, apply: bool) -> bool:
+ """Gate: writes only happen when the caller is external AND set apply."""
+ return bool(apply) and ctx.external
+
@tool(
name="propose_categorize",
@@ -48,6 +95,7 @@ _PROPOSAL_PREFACE = (
"properties": {
"transaction_ids": {"type": "array", "items": {"type": "string", "format": "uuid"}, "minItems": 1},
"category_id": {"type": "string", "format": "uuid"},
+ "apply": _APPLY_FIELD,
},
"required": ["transaction_ids", "category_id"],
"additionalProperties": False,
@@ -61,6 +109,7 @@ async def propose_categorize(
ctx: CallContext,
transaction_ids: list[str],
category_id: str,
+ apply: bool = False,
) -> dict[str, Any]:
cat_id = parse_uuid(category_id)
cat = (await session.execute(
@@ -79,7 +128,7 @@ async def propose_categorize(
"current_category_id": str(t.category_id) if t.category_id else None}
for t in txs
]
- return {
+ preview = {
"kind": "categorize",
"target_category": {"id": str(cat.id), "name": cat.name},
"affected_count": len(affected),
@@ -88,6 +137,16 @@ async def propose_categorize(
"apply_endpoint": "POST /api/transactions/categorize",
}
+ if _can_apply(ctx, apply):
+ if not affected:
+ return {**preview, "error": "no matching transactions to update"}
+ updated = await transaction_service.bulk_update_category(
+ session, ctx.user_id, [parse_uuid(a["id"]) for a in affected], cat.id
+ )
+ return {**preview, "applied": True, "updated_count": updated}
+
+ return preview
+
@tool(
name="propose_create_category",
@@ -102,6 +161,7 @@ async def propose_categorize(
"group_id": {"type": "string", "format": "uuid"},
"icon": {"type": "string"},
"color": {"type": "string", "pattern": "^#[0-9a-fA-F]{6}$"},
+ "apply": _APPLY_FIELD,
},
"required": ["name"],
"additionalProperties": False,
@@ -117,6 +177,7 @@ async def propose_create_category(
group_id: str | None = None,
icon: str | None = None,
color: str | None = None,
+ apply: bool = False,
) -> dict[str, Any]:
existing = (await session.execute(
select(Category.id, Category.name).where(
@@ -124,7 +185,7 @@ async def propose_create_category(
Category.name.ilike(name.strip()),
)
)).first()
- return {
+ preview = {
"kind": "create_category",
"proposed": {
"name": name.strip(),
@@ -136,6 +197,23 @@ async def propose_create_category(
"apply_endpoint": "POST /api/categories",
}
+ if _can_apply(ctx, apply):
+ if existing:
+ return {**preview, "error": f"category named {existing.name!r} already exists"}
+ created = await category_service.create_category(
+ session,
+ ctx.user_id,
+ CategoryCreate(
+ name=preview["proposed"]["name"],
+ group_id=parse_uuid(group_id) if group_id else None,
+ icon=preview["proposed"]["icon"],
+ color=preview["proposed"]["color"],
+ ),
+ )
+ return {**preview, "applied": True, "id": str(created.id)}
+
+ return preview
+
@tool(
name="propose_create_budget",
@@ -155,6 +233,8 @@ async def propose_create_category(
"month": {"type": "string", "format": "date"},
"amount": {"type": "number", "exclusiveMinimum": 0},
"currency": {"type": "string"},
+ "is_recurring": {"type": "boolean", "default": False},
+ "apply": _APPLY_FIELD,
},
"required": ["category_id", "month", "amount"],
"additionalProperties": False,
@@ -170,6 +250,8 @@ async def propose_create_budget(
month: str,
amount: float,
currency: str | None = None,
+ is_recurring: bool = False,
+ apply: bool = False,
) -> dict[str, Any]:
cat_id = parse_uuid(category_id)
target_month = (parse_date(month) or date.today()).replace(day=1)
@@ -180,7 +262,7 @@ async def propose_create_budget(
if cat is None:
return {"error": "category not found"}
- return {
+ preview = {
"kind": "create_budget",
"proposed": {
"category_id": str(cat.id),
@@ -188,10 +270,26 @@ async def propose_create_budget(
"month": target_month.isoformat(),
"amount": float(amount),
"currency": currency,
+ "is_recurring": is_recurring,
},
"apply_endpoint": "POST /api/budgets",
}
+ if _can_apply(ctx, apply):
+ created = await budget_service.create_budget(
+ session,
+ ctx.user_id,
+ BudgetCreate(
+ category_id=cat.id,
+ amount=Decimal(str(amount)),
+ month=target_month,
+ is_recurring=is_recurring,
+ ),
+ )
+ return {**preview, "applied": True, "id": str(created.id)}
+
+ return preview
+
@tool(
name="propose_create_transaction",
@@ -242,6 +340,7 @@ async def propose_create_budget(
"required": ["share_type", "members"],
"additionalProperties": False,
},
+ "apply": _APPLY_FIELD,
},
"required": ["description", "amount", "type", "account_id"],
"additionalProperties": False,
@@ -263,6 +362,7 @@ async def propose_create_transaction(
notes: str | None = None,
group_id: str | None = None,
splits: dict[str, Any] | None = None,
+ apply: bool = False,
) -> dict[str, Any]:
acc_id = parse_uuid(account_id)
acc = (await session.execute(
@@ -373,12 +473,50 @@ async def propose_create_transaction(
"share_type": splits["share_type"],
"items": splits_preview,
}
- return {
+ preview = {
"kind": "create_transaction",
"proposed": proposed,
"apply_endpoint": "POST /api/transactions",
}
+ if _can_apply(ctx, apply):
+ # Re-shape splits for the service. The propose tool used `member_id`
+ # but TransactionSplitInput uses `group_member_id`.
+ splits_payload: TransactionSplitsInput | None = None
+ if splits is not None:
+ splits_payload = TransactionSplitsInput(
+ share_type=splits["share_type"],
+ splits=[
+ TransactionSplitInput(
+ group_member_id=parse_uuid(m["member_id"]),
+ share_amount=Decimal(str(m["share_amount"])) if m.get("share_amount") is not None else None,
+ share_pct=Decimal(str(m["share_pct"])) if m.get("share_pct") is not None else None,
+ )
+ for m in splits["members"]
+ ],
+ )
+ try:
+ created = await transaction_service.create_transaction(
+ session,
+ ctx.user_id,
+ TransactionCreate(
+ description=proposed["description"],
+ amount=Decimal(str(amount)),
+ date=target_date,
+ type=type,
+ account_id=acc.id,
+ category_id=cat.id if cat else None,
+ currency=proposed["currency"],
+ notes=notes,
+ splits=splits_payload,
+ ),
+ )
+ except ValueError as exc:
+ return {**preview, "error": str(exc)}
+ return {**preview, "applied": True, "id": str(created.id)}
+
+ return preview
+
@tool(
name="propose_create_recurring_transaction",
@@ -400,6 +538,7 @@ async def propose_create_transaction(
"account_id": {"type": "string", "format": "uuid"},
"category_id": {"type": "string", "format": "uuid"},
"currency": {"type": "string"},
+ "apply": _APPLY_FIELD,
},
"required": ["description", "amount", "type", "frequency", "account_id"],
"additionalProperties": False,
@@ -421,6 +560,7 @@ async def propose_create_recurring_transaction(
end_date: str | None = None,
category_id: str | None = None,
currency: str | None = None,
+ apply: bool = False,
) -> dict[str, Any]:
if frequency == "monthly" and not day_of_month:
return {"error": "day_of_month is required for monthly frequency"}
@@ -437,17 +577,20 @@ async def propose_create_recurring_transaction(
if cat is None:
return {"error": "category not found"}
- return {
+ target_start = parse_date(start_date) or _today()
+ target_end = parse_date(end_date) if end_date else None
+ resolved_currency = (currency or acc.currency or "USD").upper()
+ preview = {
"kind": "create_recurring_transaction",
"proposed": {
"description": description.strip(),
"amount": float(amount),
- "currency": (currency or acc.currency or "USD").upper(),
+ "currency": resolved_currency,
"type": type,
"frequency": frequency,
"day_of_month": int(day_of_month) if day_of_month else None,
- "start_date": (parse_date(start_date) or _today()).isoformat(),
- "end_date": parse_date(end_date).isoformat() if end_date else None,
+ "start_date": target_start.isoformat(),
+ "end_date": target_end.isoformat() if target_end else None,
"account_id": str(acc.id),
"account_name": acc.name,
"category_id": str(cat.id) if cat else None,
@@ -456,6 +599,27 @@ async def propose_create_recurring_transaction(
"apply_endpoint": "POST /api/recurring-transactions",
}
+ if _can_apply(ctx, apply):
+ created = await recurring_transaction_service.create_recurring_transaction(
+ session,
+ ctx.user_id,
+ RecurringTransactionCreate(
+ description=description.strip(),
+ amount=Decimal(str(amount)),
+ currency=resolved_currency,
+ type=type,
+ frequency=frequency,
+ day_of_month=int(day_of_month) if day_of_month else None,
+ start_date=target_start,
+ end_date=target_end,
+ account_id=acc.id,
+ category_id=cat.id if cat else None,
+ ),
+ )
+ return {**preview, "applied": True, "id": str(created.id)}
+
+ return preview
+
@tool(
name="propose_update_recurring_transaction",
@@ -477,6 +641,7 @@ async def propose_create_recurring_transaction(
"end_date": {"type": "string", "format": "date"},
"category_id": {"type": "string", "format": "uuid"},
"is_active": {"type": "boolean"},
+ "apply": _APPLY_FIELD,
},
"required": ["recurring_id"],
"additionalProperties": False,
@@ -496,6 +661,7 @@ async def propose_update_recurring_transaction(
end_date: str | None = None,
category_id: str | None = None,
is_active: bool | None = None,
+ apply: bool = False,
) -> dict[str, Any]:
rid = parse_uuid(recurring_id)
rt = (await session.execute(
@@ -533,7 +699,7 @@ async def propose_update_recurring_transaction(
if not changes:
return {"error": "no changes provided"}
- return {
+ preview = {
"kind": "update_recurring_transaction",
"target": {
"id": str(rt.id),
@@ -548,6 +714,31 @@ async def propose_update_recurring_transaction(
"apply_endpoint": f"PATCH /api/recurring-transactions/{rt.id}",
}
+ if _can_apply(ctx, apply):
+ update_data: dict[str, Any] = {}
+ if "description" in changes:
+ update_data["description"] = changes["description"]
+ if "amount" in changes:
+ update_data["amount"] = Decimal(str(changes["amount"]))
+ if "frequency" in changes:
+ update_data["frequency"] = changes["frequency"]
+ if "day_of_month" in changes:
+ update_data["day_of_month"] = changes["day_of_month"]
+ if "end_date" in changes:
+ update_data["end_date"] = parse_date(changes["end_date"]) if changes["end_date"] else None
+ if "category_id" in changes:
+ update_data["category_id"] = parse_uuid(changes["category_id"])
+ if "is_active" in changes:
+ update_data["is_active"] = changes["is_active"]
+ updated = await recurring_transaction_service.update_recurring_transaction(
+ session, rt.id, ctx.user_id, RecurringTransactionUpdate(**update_data)
+ )
+ if updated is None:
+ return {**preview, "error": "recurring transaction not found"}
+ return {**preview, "applied": True, "id": str(updated.id)}
+
+ return preview
+
@tool(
name="propose_cancel_recurring_transaction",
@@ -562,6 +753,7 @@ async def propose_update_recurring_transaction(
"properties": {
"recurring_id": {"type": "string", "format": "uuid"},
"mode": {"type": "string", "enum": ["deactivate", "delete"], "default": "deactivate"},
+ "apply": _APPLY_FIELD,
},
"required": ["recurring_id"],
"additionalProperties": False,
@@ -575,6 +767,7 @@ async def propose_cancel_recurring_transaction(
ctx: CallContext,
recurring_id: str,
mode: str = "deactivate",
+ apply: bool = False,
) -> dict[str, Any]:
rt = (await session.execute(
select(RecurringTransaction).where(
@@ -590,7 +783,7 @@ async def propose_cancel_recurring_transaction(
else:
endpoint = f"PATCH /api/recurring-transactions/{rt.id} body={{is_active: false}}"
- return {
+ preview = {
"kind": "cancel_recurring_transaction",
"mode": mode,
"target": {
@@ -604,6 +797,24 @@ async def propose_cancel_recurring_transaction(
"apply_endpoint": endpoint,
}
+ if _can_apply(ctx, apply):
+ if mode == "delete":
+ ok = await recurring_transaction_service.delete_recurring_transaction(
+ session, rt.id, ctx.user_id
+ )
+ if not ok:
+ return {**preview, "error": "recurring transaction not found"}
+ return {**preview, "applied": True, "deleted": True}
+ # deactivate path
+ updated = await recurring_transaction_service.update_recurring_transaction(
+ session, rt.id, ctx.user_id, RecurringTransactionUpdate(is_active=False)
+ )
+ if updated is None:
+ return {**preview, "error": "recurring transaction not found"}
+ return {**preview, "applied": True, "id": str(updated.id), "is_active": False}
+
+ return preview
+
@tool(
name="propose_create_goal",
@@ -621,6 +832,7 @@ async def propose_cancel_recurring_transaction(
"initial_amount": {"type": "number", "minimum": 0, "description": "How much you've already saved"},
"icon": {"type": "string"},
"color": {"type": "string", "pattern": "^#[0-9a-fA-F]{6}$"},
+ "apply": _APPLY_FIELD,
},
"required": ["name", "target_amount"],
"additionalProperties": False,
@@ -639,21 +851,43 @@ async def propose_create_goal(
initial_amount: float | None = None,
icon: str | None = None,
color: str | None = None,
+ apply: bool = False,
) -> dict[str, Any]:
- return {
+ resolved_currency = (currency or "BRL").upper()
+ resolved_deadline = parse_date(deadline) if deadline else None
+ resolved_initial = float(initial_amount) if initial_amount is not None else 0.0
+ preview = {
"kind": "create_goal",
"proposed": {
"name": name.strip(),
"target_amount": float(target_amount),
- "currency": (currency or "BRL").upper(),
- "deadline": parse_date(deadline).isoformat() if deadline else None,
- "initial_amount": float(initial_amount) if initial_amount is not None else 0.0,
+ "currency": resolved_currency,
+ "deadline": resolved_deadline.isoformat() if resolved_deadline else None,
+ "initial_amount": resolved_initial,
"icon": icon or "target",
"color": color or "#3B82F6",
},
"apply_endpoint": "POST /api/goals",
}
+ if _can_apply(ctx, apply):
+ created = await goal_service.create_goal(
+ session,
+ ctx.user_id,
+ GoalCreate(
+ name=name.strip(),
+ target_amount=Decimal(str(target_amount)),
+ current_amount=Decimal(str(resolved_initial)),
+ currency=resolved_currency,
+ target_date=resolved_deadline,
+ icon=icon or "target",
+ color=color or "#3B82F6",
+ ),
+ )
+ return {**preview, "applied": True, "id": str(created.id)}
+
+ return preview
+
def _today():
from datetime import date as _d
@@ -671,6 +905,7 @@ def _today():
"properties": {
"match_pattern": {"type": "string", "description": "Substring to match in transaction description (case-insensitive)"},
"category_id": {"type": "string", "format": "uuid"},
+ "apply": _APPLY_FIELD,
},
"required": ["match_pattern", "category_id"],
"additionalProperties": False,
@@ -684,6 +919,7 @@ async def propose_create_payee_rule(
ctx: CallContext,
match_pattern: str,
category_id: str,
+ apply: bool = False,
) -> dict[str, Any]:
cat_id = parse_uuid(category_id)
cat = (await session.execute(
@@ -692,7 +928,7 @@ async def propose_create_payee_rule(
if cat is None:
return {"error": "category not found"}
- return {
+ preview = {
"kind": "create_payee_rule",
"proposed": {
"match_pattern": match_pattern,
@@ -701,3 +937,18 @@ async def propose_create_payee_rule(
},
"apply_endpoint": "POST /api/rules",
}
+
+ if _can_apply(ctx, apply):
+ created = await rule_service.create_rule(
+ session,
+ ctx.user_id,
+ RuleCreate(
+ name=f"Auto-categorize: {match_pattern}",
+ conditions_op="and",
+ conditions=[RuleCondition(field="description", op="contains", value=match_pattern)],
+ actions=[RuleAction(op="set_category", value=str(cat.id))],
+ ),
+ )
+ return {**preview, "applied": True, "id": str(created.id)}
+
+ return preview
diff --git a/backend/tests/test_agents_api.py b/backend/tests/test_agents_api.py
index affa97fd..554082c3 100644
--- a/backend/tests/test_agents_api.py
+++ b/backend/tests/test_agents_api.py
@@ -72,6 +72,53 @@ async def test_agents_info_lists_providers(client: AsyncClient, auth_headers: di
assert set(body["providers"]) >= {"openai", "anthropic", "ollama", "openai_compatible"}
+async def test_agents_info_exposes_mcp_external_ttl(client: AsyncClient, auth_headers: dict):
+ """The frontend reads mcp_external_ttl_days to label the token panel."""
+ r = await client.get("/api/agents/info", headers=auth_headers)
+ body = r.json()
+ assert isinstance(body["mcp_external_ttl_days"], int)
+ assert body["mcp_external_ttl_days"] >= 1
+
+
+# --- External MCP tokens ---------------------------------------------------
+
+async def test_mcp_tokens_requires_auth(client: AsyncClient):
+ """The mint endpoint must reject unauthenticated calls — otherwise any
+ anonymous visitor could mint a long-lived token for an arbitrary user."""
+ r = await client.post("/api/agents/mcp-tokens")
+ assert r.status_code == 401
+
+
+async def test_mcp_tokens_mint_returns_external_jwt(
+ client: AsyncClient, auth_headers: dict, test_user
+):
+ """End-to-end: minted token decodes, carries the `ext` claim, scoped
+ to the calling user, and the advertised TTL matches the response."""
+ from app.agents.mcp.auth import JWT_ALGO, JWT_AUDIENCE, JWT_ISSUER
+ from app.agents.config import get_agent_settings
+ from jose import jwt
+
+ r = await client.post("/api/agents/mcp-tokens", headers=auth_headers)
+ assert r.status_code == 201, r.text
+ body = r.json()
+ assert "token" in body
+ assert body["expires_in_days"] == get_agent_settings().mcp_external_ttl_days
+ assert body["expires_in_seconds"] == body["expires_in_days"] * 86400
+
+ payload = jwt.decode(
+ body["token"],
+ get_agent_settings().mcp_jwt_secret,
+ algorithms=[JWT_ALGO],
+ audience=JWT_AUDIENCE,
+ issuer=JWT_ISSUER,
+ )
+ assert payload["sub"] == str(test_user.id)
+ assert payload["ext"] is True
+ # External tokens are detached from any conv/agent.
+ assert "conv_id" not in payload
+ assert "agent_id" not in payload
+
+
# --- Agent CRUD ------------------------------------------------------------
async def test_unauthenticated_agents_list_rejected(client: AsyncClient):
diff --git a/backend/tests/test_agents_jwt.py b/backend/tests/test_agents_jwt.py
index 1b70e9f0..e47a1302 100644
--- a/backend/tests/test_agents_jwt.py
+++ b/backend/tests/test_agents_jwt.py
@@ -123,3 +123,27 @@ def test_optional_conv_id_is_truly_optional():
ctx = verify_request(_Req()) # type: ignore[arg-type]
assert ctx.conversation_id is None
assert ctx.agent_id is None
+
+
+def test_external_token_round_trip():
+ from mcp_server.auth import verify_request
+
+ token = mint_token(user_id=uuid.uuid4(), external=True)
+
+ class _Req:
+ headers = {"authorization": f"Bearer {token}"}
+
+ ctx = verify_request(_Req()) # type: ignore[arg-type]
+ assert ctx.external is True
+
+
+def test_default_token_has_no_external_flag():
+ from mcp_server.auth import verify_request
+
+ token = mint_token(user_id=uuid.uuid4())
+
+ class _Req:
+ headers = {"authorization": f"Bearer {token}"}
+
+ ctx = verify_request(_Req()) # type: ignore[arg-type]
+ assert ctx.external is False
diff --git a/backend/tests/test_agents_mcp_tools.py b/backend/tests/test_agents_mcp_tools.py
index 39045d93..2409be09 100644
--- a/backend/tests/test_agents_mcp_tools.py
+++ b/backend/tests/test_agents_mcp_tools.py
@@ -584,3 +584,437 @@ async def test_search_knowledge_base_requires_agent_id(
result = await handler(session=session, ctx=bare_ctx, query="anything")
assert "error" in result
assert "agent_id" in result["error"]
+
+
+# --- _can_apply gate -------------------------------------------------------
+# Authorization-critical: writes must only happen when the caller is external
+# AND set apply=True. Internal callers never write through propose_* tools.
+
+def test_can_apply_truth_table(test_user):
+ from mcp_server.tools.proposals import _can_apply
+
+ internal = CallContext(user_id=test_user.id, external=False)
+ external = CallContext(user_id=test_user.id, external=True)
+
+ assert _can_apply(internal, apply=False) is False
+ assert _can_apply(internal, apply=True) is False # internal+apply still blocked
+ assert _can_apply(external, apply=False) is False
+ assert _can_apply(external, apply=True) is True
+
+
+async def test_propose_categorize_internal_apply_does_not_write(
+ session: AsyncSession, test_user, test_transactions, test_categories
+):
+ """Internal callers (Securo's own runtime) must never mutate, even if
+ apply=True is somehow passed through."""
+ from sqlalchemy import select
+ from app.models.transaction import Transaction
+
+ handler = REGISTRY["propose_categorize"].handler
+ internal_ctx = CallContext(user_id=test_user.id, external=False)
+ tx = test_transactions[3] # uncategorized PIX RECEBIDO
+ target = test_categories[0]
+ assert tx.category_id is None
+
+ result = await handler(
+ session=session, ctx=internal_ctx,
+ transaction_ids=[str(tx.id)],
+ category_id=str(target.id),
+ apply=True,
+ )
+ assert "applied" not in result # preview only
+
+ refreshed = (await session.execute(
+ select(Transaction).where(Transaction.id == tx.id)
+ )).scalar_one()
+ assert refreshed.category_id is None
+
+
+async def test_propose_categorize_external_no_apply_returns_preview(
+ session: AsyncSession, test_user, test_transactions, test_categories
+):
+ """External caller without apply=True still gets a preview, no write."""
+ from sqlalchemy import select
+ from app.models.transaction import Transaction
+
+ handler = REGISTRY["propose_categorize"].handler
+ external_ctx = CallContext(user_id=test_user.id, external=True)
+ tx = test_transactions[3]
+ target = test_categories[0]
+
+ result = await handler(
+ session=session, ctx=external_ctx,
+ transaction_ids=[str(tx.id)],
+ category_id=str(target.id),
+ apply=False,
+ )
+ assert "applied" not in result
+
+ refreshed = (await session.execute(
+ select(Transaction).where(Transaction.id == tx.id)
+ )).scalar_one()
+ assert refreshed.category_id is None
+
+
+async def test_propose_categorize_external_apply_writes(
+ session: AsyncSession, test_user, test_transactions, test_categories
+):
+ """External caller with apply=True commits the change."""
+ from sqlalchemy import select
+ from app.models.transaction import Transaction
+
+ handler = REGISTRY["propose_categorize"].handler
+ external_ctx = CallContext(user_id=test_user.id, external=True)
+ tx = test_transactions[3]
+ target = test_categories[0]
+
+ result = await handler(
+ session=session, ctx=external_ctx,
+ transaction_ids=[str(tx.id)],
+ category_id=str(target.id),
+ apply=True,
+ )
+ assert result.get("applied") is True
+ assert result.get("updated_count") == 1
+
+ refreshed = (await session.execute(
+ select(Transaction).where(Transaction.id == tx.id)
+ )).scalar_one()
+ assert refreshed.category_id == target.id
+
+
+# --- Apply mode for the remaining propose_* tools --------------------------
+# One happy-path test per tool to catch regressions in the per-service write
+# wiring. The _can_apply gate is shared across all of them and is already
+# exercised by test_can_apply_truth_table + the propose_categorize trio.
+
+def test_every_propose_tool_advertises_apply_parameter():
+ """Schema contract: every propose_* tool must expose `apply` in its
+ JSON Schema so external clients can opt into write mode."""
+ for name, spec in REGISTRY.items():
+ if not name.startswith("propose_"):
+ continue
+ assert "apply" in spec.parameters["properties"], (
+ f"{name} is missing the `apply` parameter"
+ )
+ assert spec.parameters["properties"]["apply"]["type"] == "boolean"
+ assert spec.parameters["properties"]["apply"].get("default") is False
+
+
+async def test_propose_create_category_external_apply_writes(
+ session: AsyncSession, test_user
+):
+ from sqlalchemy import select
+ from app.models.category import Category
+
+ handler = REGISTRY["propose_create_category"].handler
+ ctx = CallContext(user_id=test_user.id, external=True)
+
+ result = await handler(
+ session=session, ctx=ctx,
+ name="Doações", icon="heart", color="#EF4444",
+ apply=True,
+ )
+ assert result.get("applied") is True
+ new_id = uuid.UUID(result["id"])
+
+ row = (await session.execute(
+ select(Category).where(Category.id == new_id, Category.user_id == test_user.id)
+ )).scalar_one()
+ assert row.name == "Doações"
+ assert row.icon == "heart"
+
+
+async def test_propose_create_category_external_apply_blocks_collision(
+ session: AsyncSession, test_user, test_categories
+):
+ """When the name collides with an existing category, apply must NOT
+ create a duplicate — the preview already flagged it."""
+ from sqlalchemy import select, func
+ from app.models.category import Category
+
+ handler = REGISTRY["propose_create_category"].handler
+ ctx = CallContext(user_id=test_user.id, external=True)
+ existing = test_categories[0]
+
+ before = (await session.execute(
+ select(func.count()).select_from(Category).where(Category.user_id == test_user.id)
+ )).scalar_one()
+
+ result = await handler(
+ session=session, ctx=ctx,
+ name=existing.name,
+ apply=True,
+ )
+ assert "applied" not in result
+ assert "error" in result
+
+ after = (await session.execute(
+ select(func.count()).select_from(Category).where(Category.user_id == test_user.id)
+ )).scalar_one()
+ assert after == before
+
+
+async def test_propose_create_budget_external_apply_writes(
+ session: AsyncSession, test_user, test_categories
+):
+ from datetime import date
+ from sqlalchemy import select
+ from app.models.budget import Budget
+
+ handler = REGISTRY["propose_create_budget"].handler
+ ctx = CallContext(user_id=test_user.id, external=True)
+ cat = test_categories[0]
+
+ result = await handler(
+ session=session, ctx=ctx,
+ category_id=str(cat.id),
+ month=date.today().replace(day=1).isoformat(),
+ amount=500.0,
+ apply=True,
+ )
+ assert result.get("applied") is True
+
+ row = (await session.execute(
+ select(Budget).where(Budget.id == uuid.UUID(result["id"]))
+ )).scalar_one()
+ assert row.category_id == cat.id
+ assert float(row.amount) == 500.0
+
+
+async def test_propose_create_transaction_external_apply_writes(
+ session: AsyncSession, test_user, test_account, test_categories
+):
+ from sqlalchemy import select
+ from app.models.transaction import Transaction
+
+ handler = REGISTRY["propose_create_transaction"].handler
+ ctx = CallContext(user_id=test_user.id, external=True)
+
+ result = await handler(
+ session=session, ctx=ctx,
+ description="Sushi delivery",
+ amount=78.50,
+ type="debit",
+ account_id=str(test_account.id),
+ category_id=str(test_categories[0].id),
+ apply=True,
+ )
+ assert result.get("applied") is True
+
+ row = (await session.execute(
+ select(Transaction).where(Transaction.id == uuid.UUID(result["id"]))
+ )).scalar_one()
+ assert row.description == "Sushi delivery"
+ assert float(row.amount) == 78.50
+ assert row.account_id == test_account.id
+
+
+async def test_propose_create_recurring_transaction_external_apply_writes(
+ session: AsyncSession, test_user, test_account
+):
+ from sqlalchemy import select
+ from app.models.recurring_transaction import RecurringTransaction
+
+ handler = REGISTRY["propose_create_recurring_transaction"].handler
+ ctx = CallContext(user_id=test_user.id, external=True)
+
+ result = await handler(
+ session=session, ctx=ctx,
+ description="Netflix",
+ amount=55.90,
+ type="debit",
+ frequency="monthly",
+ day_of_month=10,
+ account_id=str(test_account.id),
+ apply=True,
+ )
+ assert result.get("applied") is True
+
+ row = (await session.execute(
+ select(RecurringTransaction).where(
+ RecurringTransaction.id == uuid.UUID(result["id"])
+ )
+ )).scalar_one()
+ assert row.description == "Netflix"
+ assert row.frequency == "monthly"
+ assert row.day_of_month == 10
+
+
+async def test_propose_update_recurring_transaction_external_apply_writes(
+ session: AsyncSession, test_user, test_account
+):
+ """Seed a recurring tx directly, then drive an update via apply=True."""
+ from datetime import date
+ from decimal import Decimal
+ from app.models.recurring_transaction import RecurringTransaction
+
+ rt = RecurringTransaction(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ account_id=test_account.id,
+ description="Spotify",
+ amount=Decimal("21.90"),
+ currency="BRL",
+ type="debit",
+ frequency="monthly",
+ day_of_month=15,
+ start_date=date.today(),
+ next_occurrence=date.today(),
+ is_active=True,
+ )
+ session.add(rt)
+ await session.commit()
+
+ handler = REGISTRY["propose_update_recurring_transaction"].handler
+ ctx = CallContext(user_id=test_user.id, external=True)
+
+ result = await handler(
+ session=session, ctx=ctx,
+ recurring_id=str(rt.id),
+ amount=27.90,
+ apply=True,
+ )
+ assert result.get("applied") is True
+
+ await session.refresh(rt)
+ assert float(rt.amount) == 27.90
+
+
+async def test_propose_cancel_recurring_transaction_deactivate_apply(
+ session: AsyncSession, test_user, test_account
+):
+ """The default (and recommended) cancel mode flips is_active to False
+ rather than deleting the row."""
+ from datetime import date
+ from decimal import Decimal
+ from app.models.recurring_transaction import RecurringTransaction
+
+ rt = RecurringTransaction(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ account_id=test_account.id,
+ description="Old subscription",
+ amount=Decimal("10.00"),
+ currency="BRL",
+ type="debit",
+ frequency="monthly",
+ day_of_month=1,
+ start_date=date.today(),
+ next_occurrence=date.today(),
+ is_active=True,
+ )
+ session.add(rt)
+ await session.commit()
+
+ handler = REGISTRY["propose_cancel_recurring_transaction"].handler
+ ctx = CallContext(user_id=test_user.id, external=True)
+
+ result = await handler(
+ session=session, ctx=ctx,
+ recurring_id=str(rt.id),
+ mode="deactivate",
+ apply=True,
+ )
+ assert result.get("applied") is True
+ assert result.get("is_active") is False
+
+ await session.refresh(rt)
+ assert rt.is_active is False
+
+
+async def test_propose_cancel_recurring_transaction_delete_apply(
+ session: AsyncSession, test_user, test_account
+):
+ """The 'delete' mode removes the row entirely."""
+ from datetime import date
+ from decimal import Decimal
+ from sqlalchemy import select
+ from app.models.recurring_transaction import RecurringTransaction
+
+ rt = RecurringTransaction(
+ id=uuid.uuid4(),
+ user_id=test_user.id,
+ account_id=test_account.id,
+ description="Throwaway",
+ amount=Decimal("5.00"),
+ currency="BRL",
+ type="debit",
+ frequency="monthly",
+ day_of_month=1,
+ start_date=date.today(),
+ next_occurrence=date.today(),
+ is_active=True,
+ )
+ session.add(rt)
+ await session.commit()
+ rt_id = rt.id
+
+ handler = REGISTRY["propose_cancel_recurring_transaction"].handler
+ ctx = CallContext(user_id=test_user.id, external=True)
+
+ result = await handler(
+ session=session, ctx=ctx,
+ recurring_id=str(rt_id),
+ mode="delete",
+ apply=True,
+ )
+ assert result.get("applied") is True
+ assert result.get("deleted") is True
+
+ gone = (await session.execute(
+ select(RecurringTransaction).where(RecurringTransaction.id == rt_id)
+ )).scalar_one_or_none()
+ assert gone is None
+
+
+async def test_propose_create_goal_external_apply_writes(
+ session: AsyncSession, test_user
+):
+ from sqlalchemy import select
+ from app.models.goal import Goal
+
+ handler = REGISTRY["propose_create_goal"].handler
+ ctx = CallContext(user_id=test_user.id, external=True)
+
+ result = await handler(
+ session=session, ctx=ctx,
+ name="Travel fund",
+ target_amount=10000.0,
+ currency="BRL",
+ apply=True,
+ )
+ assert result.get("applied") is True
+
+ row = (await session.execute(
+ select(Goal).where(Goal.id == uuid.UUID(result["id"]))
+ )).scalar_one()
+ assert row.name == "Travel fund"
+ assert float(row.target_amount) == 10000.0
+
+
+async def test_propose_create_payee_rule_external_apply_writes(
+ session: AsyncSession, test_user, test_categories
+):
+ """The rule wrapper translates (match_pattern, category_id) into the
+ conditions/actions shape RuleCreate expects."""
+ from sqlalchemy import select
+ from app.models.rule import Rule
+
+ handler = REGISTRY["propose_create_payee_rule"].handler
+ ctx = CallContext(user_id=test_user.id, external=True)
+ cat = test_categories[0]
+
+ result = await handler(
+ session=session, ctx=ctx,
+ match_pattern="UBER",
+ category_id=str(cat.id),
+ apply=True,
+ )
+ assert result.get("applied") is True
+
+ row = (await session.execute(
+ select(Rule).where(Rule.id == uuid.UUID(result["id"]))
+ )).scalar_one()
+ assert any(c.get("value") == "UBER" for c in row.conditions)
+ assert any(a.get("value") == str(cat.id) for a in row.actions)
diff --git a/docker-compose.yml b/docker-compose.yml
index e95d9630..49c954a2 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -19,6 +19,9 @@ x-backend-env: &backend-env
AGENTS_BUILTIN_MCP_URL: ${AGENTS_BUILTIN_MCP_URL:-http://mcp-server:8765/mcp}
AGENTS_EXTRA_MCP_SERVERS: ${AGENTS_EXTRA_MCP_SERVERS:-}
AGENTS_MCP_JWT_SECRET: ${AGENTS_MCP_JWT_SECRET:-dev-mcp-secret-change-in-production}
+ # TTL for tokens minted from /agents/connections → "External MCP access".
+ # Used by Claude Desktop, n8n, custom clients plugging into Securo.
+ AGENTS_MCP_EXTERNAL_TTL_DAYS: ${AGENTS_MCP_EXTERNAL_TTL_DAYS:-90}
# LLM provider config — only the provider you actually use needs setting.
AGENTS_DEFAULT_PROVIDER: ${AGENTS_DEFAULT_PROVIDER:-ollama}
AGENTS_DEFAULT_MODEL: ${AGENTS_DEFAULT_MODEL:-}
@@ -111,12 +114,17 @@ services:
# profile (`docker compose --profile agents up`). Reuses the backend
# image, just runs a different uvicorn entry point. Modular by design —
# users not using the agents feature pay zero cost.
+ #
+ # The port is published on the host (127.0.0.1 by default) so external
+ # agents — Claude Desktop, n8n, custom clients — can reach it after
+ # minting a token from the UI. JWT auth is always required. Override
+ # AGENTS_MCP_EXTERNAL_HOST_PORT to e.g. "0.0.0.0:8765" to expose to LAN.
mcp-server:
<<: *backend-base
profiles: [agents]
command: uvicorn mcp_server.main:app --host 0.0.0.0 --port 8765
- expose:
- - "8765"
+ ports:
+ - "${AGENTS_MCP_EXTERNAL_HOST_PORT:-127.0.0.1:8765}:8765"
volumes:
pgdata:
diff --git a/frontend/src/components/agents/mcp-external-panel.tsx b/frontend/src/components/agents/mcp-external-panel.tsx
new file mode 100644
index 00000000..ecd0ccad
--- /dev/null
+++ b/frontend/src/components/agents/mcp-external-panel.tsx
@@ -0,0 +1,200 @@
+import { useState } from 'react'
+import { useMutation, useQuery } from '@tanstack/react-query'
+import { useTranslation } from 'react-i18next'
+import { Check, Copy, KeyRound, Plug } from 'lucide-react'
+import { toast } from 'sonner'
+import { Button } from '@/components/ui/button'
+import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
+import { agents } from '@/lib/api'
+
+type Snippet = { label: string; value: string }
+type ClientId = 'claude' | 'openai'
+
+function CopyButton({ value }: { value: string }) {
+ const { t } = useTranslation()
+ const [copied, setCopied] = useState(false)
+ return (
+ <button
+ type="button"
+ onClick={async () => {
+ try {
+ await navigator.clipboard.writeText(value)
+ setCopied(true)
+ setTimeout(() => setCopied(false), 1500)
+ } catch {
+ toast.error(t('agents.mcpExternal.copyFailed', 'Copy failed'))
+ }
+ }}
+ className="absolute top-2 right-2 inline-flex items-center gap-1 rounded-md border border-border bg-background/80 px-2 py-1 text-[11px] text-muted-foreground hover:text-foreground transition-colors"
+ >
+ {copied ? <Check className="h-3 w-3" /> : <Copy className="h-3 w-3" />}
+ {copied ? t('agents.mcpExternal.copied', 'Copied') : t('agents.mcpExternal.copy', 'Copy')}
+ </button>
+ )
+}
+
+function CodeBlock({ value }: { value: string }) {
+ return (
+ <div className="relative">
+ <pre className="bg-muted/50 border border-border rounded-md p-3 pr-16 text-[12px] leading-relaxed overflow-x-auto whitespace-pre">
+ <code>{value}</code>
+ </pre>
+ <CopyButton value={value} />
+ </div>
+ )
+}
+
+// Builds the per-client integration snippet. Kept as a function so the
+// shapes stay co-located with their labels and easy to extend.
+function clientConfigFor(client: ClientId, url: string, token: string): string {
+ if (client === 'claude') {
+ // Works for Claude Desktop, Claude Code (.mcp.json), and Cursor.
+ return JSON.stringify(
+ {
+ mcpServers: {
+ securo: {
+ url,
+ headers: { Authorization: `Bearer ${token}` },
+ },
+ },
+ },
+ null,
+ 2,
+ )
+ }
+ // OpenAI Responses API tool spec — paste into the `tools` array of
+ // your API call. ChatGPT.com itself adds MCP via the Connectors UI,
+ // not a JSON paste.
+ return JSON.stringify(
+ {
+ type: 'mcp',
+ server_label: 'securo',
+ server_url: url,
+ headers: { Authorization: `Bearer ${token}` },
+ require_approval: 'never',
+ },
+ null,
+ 2,
+ )
+}
+
+export function McpExternalPanel() {
+ const { t } = useTranslation()
+ const { data: info } = useQuery({ queryKey: ['agents-info'], queryFn: () => agents.info() })
+ const [result, setResult] = useState<{ token: string; expiresInDays: number } | null>(null)
+ const [client, setClient] = useState<ClientId>('claude')
+
+ const mintMut = useMutation({
+ mutationFn: () => agents.mcpTokens.create(),
+ onSuccess: (res) => {
+ setResult({ token: res.token, expiresInDays: res.expires_in_days })
+ },
+ onError: () => toast.error(t('agents.mcpExternal.mintFailed', 'Could not mint token')),
+ })
+
+ if (!info) return null
+
+ const url = `${window.location.protocol}//${window.location.hostname}:8765/mcp`
+
+ // The first three snippets are universal regardless of client choice.
+ const universalSnippets: Snippet[] = result
+ ? [
+ { label: t('agents.mcpExternal.snippets.token', 'Token'), value: result.token },
+ { label: t('agents.mcpExternal.snippets.url', 'MCP endpoint'), value: url },
+ {
+ label: t('agents.mcpExternal.snippets.curl', 'curl example'),
+ value: `curl -X POST ${url} \\\n -H "Authorization: Bearer ${result.token}" \\\n -H "Content-Type: application/json" \\\n -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'`,
+ },
+ ]
+ : []
+
+ const clientTabs: { id: ClientId; label: string }[] = [
+ { id: 'claude', label: t('agents.mcpExternal.clients.claude', 'Claude Desktop / Code / Cursor') },
+ { id: 'openai', label: t('agents.mcpExternal.clients.openai', 'OpenAI Responses API') },
+ ]
+
+ return (
+ <div className="mt-8 bg-card rounded-xl border border-border shadow-sm overflow-hidden">
+ <div className="flex items-start gap-3 px-4 sm:px-5 py-4 border-b border-border">
+ <div className="h-10 w-10 rounded-md bg-muted flex items-center justify-center shrink-0">
+ <Plug className="h-5 w-5 text-muted-foreground" />
+ </div>
+ <div className="flex-1 min-w-0">
+ <h2 className="text-base font-semibold">
+ {t('agents.mcpExternal.title', 'External MCP access')}
+ </h2>
+ <p className="text-sm text-muted-foreground mt-1">
+ {t(
+ 'agents.mcpExternal.subtitle',
+ "Plug an external agent (Claude Desktop, ChatGPT, n8n, a custom client) into Securo's built-in MCP server. The token below is scoped to your user and expires in {{days}} days.",
+ { days: info.mcp_external_ttl_days },
+ )}
+ </p>
+ </div>
+ </div>
+
+ <div className="px-4 sm:px-5 py-4 space-y-4">
+ {!result ? (
+ <Button
+ size="sm"
+ className="gap-1.5 h-8"
+ onClick={() => mintMut.mutate()}
+ disabled={mintMut.isPending}
+ >
+ <KeyRound size={13} />
+ {mintMut.isPending
+ ? t('agents.mcpExternal.minting', 'Generating…')
+ : t('agents.mcpExternal.mint', 'Generate token')}
+ </Button>
+ ) : (
+ <>
+ <div className="text-xs text-muted-foreground">
+ {t(
+ 'agents.mcpExternal.warning',
+ "Copy now — Securo does not store the token, so we can't show it again. Revoke by rotating AGENTS_MCP_JWT_SECRET.",
+ )}
+ </div>
+ {universalSnippets.map((s) => (
+ <div key={s.label}>
+ <div className="text-xs font-medium text-muted-foreground mb-1.5">{s.label}</div>
+ <CodeBlock value={s.value} />
+ </div>
+ ))}
+
+ <div>
+ <div className="text-xs font-medium text-muted-foreground mb-1.5">
+ {t('agents.mcpExternal.snippets.clientConfig', 'Client integration')}
+ </div>
+ <Tabs value={client} onValueChange={(v) => setClient(v as ClientId)}>
+ <TabsList className="h-8">
+ {clientTabs.map((tab) => (
+ <TabsTrigger key={tab.id} value={tab.id} className="text-xs px-2.5 py-1">
+ {tab.label}
+ </TabsTrigger>
+ ))}
+ </TabsList>
+ {clientTabs.map((tab) => (
+ <TabsContent key={tab.id} value={tab.id} className="mt-2">
+ <CodeBlock value={clientConfigFor(tab.id, url, result.token)} />
+ </TabsContent>
+ ))}
+ </Tabs>
+ </div>
+
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-8 text-xs"
+ onClick={() => {
+ setResult(null)
+ mintMut.reset()
+ }}
+ >
+ {t('agents.mcpExternal.regenerate', 'Generate another')}
+ </Button>
+ </>
+ )}
+ </div>
+ </div>
+ )
+}
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 15c4ea92..9efdf59d 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -1106,8 +1106,15 @@ export const agents = {
default_top_n: number
default_similarity_threshold: number
extra_mcp_servers_configured: boolean
+ mcp_external_ttl_days: number
}
},
+ mcpTokens: {
+ create: async (): Promise<{ token: string; expires_in_seconds: number; expires_in_days: number }> => {
+ const { data } = await api.post('/agents/mcp-tokens')
+ return data
+ },
+ },
list: async (includeArchived = false): Promise<Agent[]> => {
const { data } = await api.get('/agents', { params: { include_archived: includeArchived } })
return data
diff --git a/frontend/src/pages/agent-connections.tsx b/frontend/src/pages/agent-connections.tsx
index 77938f77..1d55b927 100644
--- a/frontend/src/pages/agent-connections.tsx
+++ b/frontend/src/pages/agent-connections.tsx
@@ -10,6 +10,7 @@ import { PageHeader } from '@/components/page-header'
import { agents } from '@/lib/api'
import type { LlmConnection } from '@/lib/api'
import { ConnectionFormDialog } from '@/components/agents/connection-form-dialog'
+import { McpExternalPanel } from '@/components/agents/mcp-external-panel'
export default function AgentConnectionsPage() {
const { t } = useTranslation()
@@ -152,6 +153,8 @@ export default function AgentConnectionsPage() {
</div>
)}
+ <McpExternalPanel />
+
<ConnectionFormDialog open={createOpen} onOpenChange={setCreateOpen} />
<ConnectionFormDialog
open={!!editing}