Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
137 changes: 104 additions & 33 deletions docs/reference/agent-tools.md

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions docs/reference/confluence-wrapper.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

> Gateway REST surface that gives sandboxed agents **read-only** access to Confluence. Mirrors the `/api/v1/jira/*` pattern from [#1556](https://github.com/jwbron/egg/issues/1556): Atlassian credentials live in the gateway, the sandbox posts session-authenticated JSON, and every call is funneled through a private-mode gate, a **space allowlist**, a verb allowlist, and structured audit logs.

> **Two front-ends, one route surface.** Sandbox agents reach these routes via either the `mcp__confluence__*` MCP tools ([#2994](https://github.com/jwbron/egg/issues/2994)) — preferred, because they appear in the agent's tool manifest every turn — or the `sandbox/scripts/confluence` bash wrapper. Both POST the identical bodies documented below; the MCP layer holds no credentials and adds no capability (it's a presentation layer over these routes). See [Agent MCP Tools → `mcp__confluence__*`](agent-tools.md#mcp__confluence__--confluence-reads-gateway-backed-2994). This doc is the source of truth for the **route surface and policy**; the MCP tools translate snake_case args (`page_id`, `space_key`, `cql`, `body_format`) to the camelCase bodies below.

v1 is read-only — eight `POST /api/v1/confluence/*` routes covering page reads, descendants, footer/inline comments, space listings, CQL search, and a regex-allowlisted GET-only `/execute` escape hatch. Write verbs (`page/create`, `page/update`, `comment/create`) are scoped as a follow-up and drop in as three additional narrow routes under the same decorators and policy plumbing — no re-architecting. Attachments, restrictions, permissions, space-admin verbs, user enumeration, and `PUT` / `PATCH` / `DELETE` methods are **permanently out of scope** and are enforced at the path validator.

The wrapper is a **v2-first hybrid** with transparent v1 fallbacks for two known v2 quirks:
Expand Down
2 changes: 2 additions & 0 deletions docs/reference/jira-wrapper.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

> Gateway REST surface that gives sandboxed agents bounded access to Jira. Mirrors the `/api/v1/gh/*` pattern: Atlassian credentials live in the gateway, the sandbox posts session-authenticated JSON, and every call is funneled through a private-mode gate, a project allowlist, and structured audit logs.

> **Two front-ends, one route surface.** Sandbox agents reach these routes via either the `mcp__jira__*` MCP tools ([#2994](https://github.com/jwbron/egg/issues/2994)) — preferred, because they appear in the agent's tool manifest every turn — or the `sandbox/scripts/jira` bash wrapper. Both POST the identical bodies documented below; the MCP layer holds no credentials and adds no capability (it's a presentation layer over these routes). The operator-only `ticket/transition` route is **not** exposed via MCP (the bash wrapper doesn't surface it either). See [Agent MCP Tools → `mcp__jira__*`](agent-tools.md#mcp__jira__--jira-reads--writes-gateway-backed-2994). This doc is the source of truth for the **route surface and policy**; the MCP tools translate snake_case args (`ticket`, `jql`, `issue_type`, `add_labels`) to the camelCase bodies below.

The original v1 surface ([#1556](https://github.com/jwbron/egg/issues/1556)) was read-only. The bounded write extension ([#1924](https://github.com/jwbron/egg/issues/1924)) adds four narrow write routes — `ticket/create`, `ticket/edit`, `ticket/comment/add`, `issue-link/create` — under the same decorators and policy plumbing. All write verbs share the read verbs' private-mode + project-allowlist + audit chain; see [Write verbs](#write-verbs) for the per-route body schema, ADF wrapping rules, idempotency-key semantics, and the audit-log redaction contract for write payloads. Transitions, worklogs, attachments, watchers, deletions, and `DELETE` methods are **permanently out of scope** and are enforced at the path validator. `PUT` / `PATCH` are blocked from the `/execute` passthrough but used internally by `JiraClient.edit_issue` against `PUT /rest/api/3/issue/{key}` (the validator is bypassed for hardcoded write methods).

## Endpoint surface
Expand Down
12 changes: 8 additions & 4 deletions sandbox/agent-config/rules/environment.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,11 @@ All git/gh operations routed through gateway. Key restrictions:

If push fails: check `git remote -v` is HTTPS, check `curl http://egg-gateway:9848/api/v1/health`, verify branch is egg-owned.

### Jira Wrapper (`jira`)
### Jira (`mcp__jira__*` tools / `jira` wrapper)

The `sandbox/scripts/jira` wrapper is the only way for the sandbox to reach Jira — it POSTs to the gateway's `/api/v1/jira/*` routes with `Authorization: Bearer $EGG_SESSION_TOKEN` and Atlassian credentials never enter the sandbox. **Private network mode only**: in public mode every Jira call returns 403 `private_mode_required` before any upstream request.
The sandbox reaches Jira through the gateway's `/api/v1/jira/*` routes (`Authorization: Bearer $EGG_SESSION_TOKEN`; Atlassian credentials never enter the sandbox). **Private network mode only**: in public mode every Jira call returns 403 `private_mode_required` before any upstream request.

**Reach for the `mcp__jira__*` MCP tools first** (`mcp__jira__ticket_get`, `mcp__jira__search`, `mcp__jira__ticket_comments`, `mcp__jira__ticket_create`, `mcp__jira__ticket_edit`, `mcp__jira__ticket_comment_add`, `mcp__jira__link_create`, `mcp__jira__ticket_remotelinks`, `mcp__jira__execute`). They appear in your tool manifest every turn (no need to recall this doc), take snake_case args (`ticket`, `jql`, `max_results`, `fields`, …), and hit the same gateway routes under the same policy. The `sandbox/scripts/jira` shell wrapper below remains available for ad-hoc debugging and is the source of truth for the verb/route surface (#2994).

| Verb | Gateway route |
|------|---------------|
Expand Down Expand Up @@ -75,9 +77,11 @@ jira search 'project = ENG OR project = SEC'

**Hard limits (always denied):** `transitions`, `worklog`, `attachments`, `watchers`, HTTP `DELETE` (no exposed surface), path traversal (`..`), duplicate slashes, non-ASCII keys. The `/execute` passthrough is GET-only (`PUT` / `PATCH` return 403 there); the four write routes (`ticket/create`, `ticket/edit`, `ticket/comment/add`, `issue-link/create`) use their own dedicated paths and are the only write surface. See [Jira Wrapper Reference](../../../docs/reference/jira-wrapper.md) for the full endpoint surface, write verb body schemas, idempotency keys, and the `not_found` envelope.

### Confluence Wrapper (`confluence`)
### Confluence (`mcp__confluence__*` tools / `confluence` wrapper)

The sandbox reaches Confluence through the gateway's `/api/v1/confluence/*` routes (`Authorization: Bearer $EGG_SESSION_TOKEN`; Atlassian credentials never enter the sandbox). **Private network mode only**: in public mode every Confluence call returns 403 `private_mode_required` before any upstream request.

The `sandbox/scripts/confluence` wrapper is the only way for the sandbox to reach Confluence — it POSTs to the gateway's `/api/v1/confluence/*` routes with `Authorization: Bearer $EGG_SESSION_TOKEN` and Atlassian credentials never enter the sandbox. **Private network mode only**: in public mode every Confluence call returns 403 `private_mode_required` before any upstream request.
**Reach for the `mcp__confluence__*` MCP tools first** (`mcp__confluence__page_get`, `mcp__confluence__search`, `mcp__confluence__space_list`, `mcp__confluence__space_pages`, `mcp__confluence__page_descendants`, `mcp__confluence__page_footer_comments`, `mcp__confluence__page_inline_comments`, `mcp__confluence__execute`). They appear in your tool manifest every turn, so **don't guess which spaces exist — call `mcp__confluence__space_list`**, which returns the allowlisted set (the failure #2994 fixes). They take snake_case args (`page_id`, `space_key`, `cql`, `body_format`, …) and hit the same gateway routes under the same policy. The `sandbox/scripts/confluence` shell wrapper below remains available for ad-hoc debugging and is the source of truth for the verb/route surface (#2994).

| Verb | Gateway route |
|------|---------------|
Expand Down
34 changes: 34 additions & 0 deletions sandbox/egg_agent_tools/handlers/_gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,40 @@ def gateway_request(
raise GatewayError("Request to gateway timed out") from exc


def gateway_data_request(
endpoint: str,
*,
body: dict[str, Any] | None = None,
timeout: int = 30,
) -> Any:
"""POST ``body`` to a gateway route and return the unwrapped ``data``.

The Atlassian gateway routes (``/api/v1/{confluence,jira}/*``) all
answer with the standard ``{success, message, data, details}``
envelope (``make_success`` / ``make_error`` in ``gateway/gateway.py``)
and use HTTP status codes for failures. :func:`gateway_request`
already raises :class:`GatewayError` on any non-2xx response, so on
the happy path we simply hand the caller the upstream ``data``
payload — exactly what the ``confluence`` / ``jira`` shell wrappers
print on success (their ``call_gateway`` emits ``data`` as JSON).

The ``success`` re-check is defence-in-depth for the unlikely case of
a 2xx body that still flags ``success: false``; the not-found envelope
is *not* such a case (the gateway returns ``success: true`` with
``data.status == "not_found"``), so it flows through untouched.
"""
result = gateway_request(endpoint, method="POST", data=body or {}, timeout=timeout)
if isinstance(result, dict) and result.get("success") is False:
details = result.get("details")
raise GatewayError(
result.get("message", "gateway request failed"),
details=details if isinstance(details, dict) else None,
)
if isinstance(result, dict):
return result.get("data", result)
return result


def orchestrator_request(
endpoint: str,
*,
Expand Down
198 changes: 198 additions & 0 deletions sandbox/egg_agent_tools/handlers/confluence.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
"""Confluence handlers — gateway-backed reads for sandbox agents (#2994).

These mirror the verbs in the ``sandbox/scripts/confluence`` shell
wrapper one-for-one, POSTing to the same ``/api/v1/confluence/*`` gateway
routes with the session token :mod:`egg_agent_tools.handlers._gateway`
already resolves. They hold **no Atlassian credentials** and add **no
new capability** — the gateway still enforces the space allowlist,
read-only policy, CQL scope extraction, response redaction, and the
private-network-mode gate. This is a presentation layer that makes the
routes discoverable as ``mcp__confluence__*`` tools (the bash wrapper is
prose an agent has to recall; an MCP tool is in the manifest every turn).

Each handler accepts snake_case request keys (the convention every other
egg MCP tool uses) and translates them to the camelCase field names the
gateway expects. None of these verbs has a Python ``egg-*`` CLI
counterpart the MCP↔CLI drift test can walk — the human-facing analog is
the bash ``confluence`` wrapper, not an argparse parser — so every
registration sets ``cli_command=None`` and each docstring records the
"no CLI" rationale required by the decision-13 drift gate.
"""

from __future__ import annotations

from typing import Any

from egg_agent_tools.handlers._gateway import gateway_data_request
from egg_agent_tools.handlers.errors import HandlerError


def _as_str_list(value: Any) -> list[str] | None:
"""Normalise a list-or-CSV-string into a clean ``list[str]`` (or None).

The agent-facing schema asks for an array, but a model occasionally
passes the gateway's comma-separated form; accept both so a stray
``"storage,view"`` doesn't 400 at the gateway.
"""
if value is None:
return None
if isinstance(value, str):
items = [v.strip() for v in value.split(",")]
elif isinstance(value, (list, tuple)):
items = [str(v).strip() for v in value]
else:
raise HandlerError(f"expected a string or list of strings, got {type(value).__name__}")
cleaned = [v for v in items if v]
return cleaned or None


def _require_str(req: dict[str, Any], key: str, label: str) -> str:
value = req.get(key)
if not isinstance(value, str) or not value.strip():
raise HandlerError(f"{label} is required (pass '{key}')")
return value.strip()


def confluence_page_get(req: dict[str, Any]) -> Any:
"""Fetch a Confluence page by numeric ``page_id`` (no CLI counterpart).

Mirrors ``confluence page get`` → ``POST /api/v1/confluence/page/get``.
Optional ``body_format`` (list, default ``storage`` server-side) and
``expand`` select the rendition and extra fields.
"""
body: dict[str, Any] = {"pageId": _require_str(req, "page_id", "page_id")}
body_format = _as_str_list(req.get("body_format"))
if body_format:
body["bodyFormat"] = body_format
expand = _as_str_list(req.get("expand"))
if expand:
body["expand"] = expand
return gateway_data_request("/api/v1/confluence/page/get", body=body)


def confluence_page_descendants(req: dict[str, Any]) -> Any:
"""List the descendants of a Confluence page (no CLI counterpart).

Mirrors ``confluence page descendants`` →
``POST /api/v1/confluence/page/descendants``. Paginated via ``limit``
+ opaque ``cursor``; ``depth`` bounds the tree walk.
"""
body: dict[str, Any] = {"pageId": _require_str(req, "page_id", "page_id")}
if req.get("depth") is not None:
body["depth"] = req["depth"]
if req.get("limit") is not None:
body["limit"] = int(req["limit"])
if req.get("cursor"):
body["cursor"] = req["cursor"]
return gateway_data_request("/api/v1/confluence/page/descendants", body=body)


def confluence_page_footer_comments(req: dict[str, Any]) -> Any:
"""Fetch footer comments on a Confluence page (no CLI counterpart).

Mirrors ``confluence page footer-comments`` →
``POST /api/v1/confluence/page/footer-comments``. Set
``include_replies`` to inline threaded replies.
"""
body: dict[str, Any] = {
"pageId": _require_str(req, "page_id", "page_id"),
"includeReplies": bool(req.get("include_replies", False)),
}
body_format = _as_str_list(req.get("body_format"))
if body_format:
body["bodyFormat"] = body_format
if req.get("limit") is not None:
body["limit"] = int(req["limit"])
if req.get("cursor"):
body["cursor"] = req["cursor"]
return gateway_data_request("/api/v1/confluence/page/footer-comments", body=body)


def confluence_page_inline_comments(req: dict[str, Any]) -> Any:
"""Fetch inline comments on a Confluence page (no CLI counterpart).

Mirrors ``confluence page inline-comments`` →
``POST /api/v1/confluence/page/inline-comments``. The gateway
transparently retries against the v1 API when v2 returns 404 and
flags ``used_fallback`` on the response.
"""
body: dict[str, Any] = {"pageId": _require_str(req, "page_id", "page_id")}
body_format = _as_str_list(req.get("body_format"))
if body_format:
body["bodyFormat"] = body_format
if req.get("limit") is not None:
body["limit"] = int(req["limit"])
if req.get("cursor"):
body["cursor"] = req["cursor"]
return gateway_data_request("/api/v1/confluence/page/inline-comments", body=body)


def confluence_space_pages(req: dict[str, Any]) -> Any:
"""List pages in a Confluence space (no CLI counterpart).

Mirrors ``confluence space pages`` →
``POST /api/v1/confluence/space/pages``. The space must be on the
operator's allowlist or the gateway returns 403.
"""
body: dict[str, Any] = {"spaceKey": _require_str(req, "space_key", "space_key")}
if req.get("limit") is not None:
body["limit"] = int(req["limit"])
if req.get("cursor"):
body["cursor"] = req["cursor"]
body_format = _as_str_list(req.get("body_format"))
if body_format:
body["bodyFormat"] = body_format
return gateway_data_request("/api/v1/confluence/space/pages", body=body)


def confluence_space_list(req: dict[str, Any]) -> Any:
"""List the Confluence spaces visible to the agent (no CLI counterpart).

Mirrors ``confluence space list`` →
``POST /api/v1/confluence/space/list``. The response is filtered to
the operator's allowlist — this is the verb that answers "which
spaces can I read?" without guessing (the #2994 motivating failure).
"""
body: dict[str, Any] = {}
if req.get("limit") is not None:
body["limit"] = int(req["limit"])
if req.get("cursor"):
body["cursor"] = req["cursor"]
return gateway_data_request("/api/v1/confluence/space/list", body=body)


def confluence_search(req: dict[str, Any]) -> Any:
"""Run a CQL query (no CLI counterpart).

Mirrors ``confluence search`` → ``POST /api/v1/confluence/search``.
The CQL must statically scope to allowlisted spaces; the gateway's
scope extractor denies on ambiguity (any ``OR`` over ``space``).
"""
body: dict[str, Any] = {"cql": _require_str(req, "cql", "cql")}
if req.get("limit") is not None:
body["limit"] = int(req["limit"])
if req.get("cursor"):
body["cursor"] = req["cursor"]
return gateway_data_request("/api/v1/confluence/search", body=body)


def confluence_execute(req: dict[str, Any]) -> Any:
"""Raw read-only Confluence REST passthrough (no CLI counterpart).

Mirrors ``confluence execute`` → ``POST /api/v1/confluence/execute``.
GET-only escape hatch for routes without a dedicated verb; the
gateway rejects non-GET methods and denied paths with 403.
"""
body: dict[str, Any] = {
"method": _require_str(req, "method", "method"),
"path": _require_str(req, "path", "path"),
}
query = req.get("query")
if query is not None:
if not isinstance(query, dict):
raise HandlerError("'query' must be an object of string key/value pairs")
body["query"] = query
request_body = req.get("body")
if request_body is not None:
body["body"] = request_body
return gateway_data_request("/api/v1/confluence/execute", body=body)
Loading
Loading