Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(marketplace): run Slack through a native Web API tool

rubenluetke10-beep682097bae199
diff --git a/docs/adr/0011-router-pure-dispatcher.md b/docs/adr/0011-router-pure-dispatcher.md
index 90075d16f2..960b600610 100644
--- a/docs/adr/0011-router-pure-dispatcher.md
+++ b/docs/adr/0011-router-pure-dispatcher.md
@@ -1428,3 +1428,26 @@ Mission workers lose the `awareness-recall` grant (ADR-0030).
- `tests/unit/brain/test_routing.py` (exact router set)
- `tests/unit/brain/test_evidence_gate.py`, `tests/unit/brain/test_evidence_gate_wiring.py` (honest refusal for the `activity` domain)
- `tests/missions/test_worker_capability_parity.py` (the worker grant)
+
+## Amendment 2026-10-05 — Marketplace native tool `slack`
+
+The Slack plugin used to execute through Slack's hosted MCP server. Slack
+admits only Marketplace-listed or internal apps to that server; the shared
+publisher app is publicly distributed but unlisted, so every end user would
+be refused. The catalog entry therefore drops its MCP server block and binds
+`"native_tool": "slack"`, a REST tool over the Slack Web API that uses the
+same marketplace user token. With no MCP server block, the virtual
+`mcp-tools`/`plugin-tools` loaders expand to nothing for Slack, so `slack`
+joins `ROUTER_TOOLS` directly, for the same reason as the other marketplace
+native tools.
+
+| Tool | Added | Backing | Risk | Recursion guard? |
+|---|---|---|---|---|
+| `slack` | 2026-10-05 | Slack Web API (`search.messages`, `conversations.*`, `users.*`, `chat.postMessage`) via the marketplace user token with rotation refresh | `ask` statically; every read downgrades to `safe` via `risk_tier_for_args`; `post_message` stays `ask` (echo-confirm) | n/a — a direct REST call, never a spawn; router-tier only (AP-5/AP-14) |
+
+### Regression guards
+
+- `tests/unit/plugins/tool/test_slack_rest.py` — `ok: false` mapping without
+ echoing provider text, `token_expired` → one refresh + retry, `Retry-After`
+ handling, cursor pagination, channel/DM resolution, per-action risk tiers.
+- `tests/unit/brain/test_routing.py` (exact router set includes `slack`).
diff --git a/docs/marketplace/plugin-auth-audit.md b/docs/marketplace/plugin-auth-audit.md
index 6d9ce8bd3d..d0be6a5759 100644
--- a/docs/marketplace/plugin-auth-audit.md
+++ b/docs/marketplace/plugin-auth-audit.md
@@ -26,7 +26,7 @@ Twenty-six further hosted MCP services (Atlassian, Sentry, PayPal, Zapier and ot
| `vercel` (Vercel) | Connect entry observed; completion blocked | Provider page reached; authorization incomplete | Not verified | Not verified | Not run | Not completed | Windows UI only; other OSes not exercised | **BLOCKED** | Provider account sign-in has not been completed. **Owner:** Provider account holder. **Next:** Complete official sign-in and consent, then verify all seven stages with a real read-only plugin action. Observation: Connect opened official vercel.com/oauth/authorize; provider sign-in required. No user token or client setup. |
| `supabase` (Supabase) | Connect entry observed; completion blocked | Provider page reached; authorization incomplete | Not verified | Not verified | Not run | Not completed | Windows UI only; other OSes not exercised | **BLOCKED** | Provider account sign-in has not been completed. **Owner:** Provider account holder. **Next:** Complete official sign-in and consent, then verify all seven stages with a real read-only plugin action. Observation: Connect opened supabase.com/dashboard/sign-in via provider DCR. Account sign-in required. |
| `notion` (Notion) | Reconnect entry only; existing connection retained | Provider page reached; authorization incomplete | Not verified | Existing state only; new grant not verified | PASS: notion/notion-fetch; existing grant | Not completed | Windows UI only; other OSes not exercised | **BLOCKED** | Official provider consent page reached; a new resource access grant awaits explicit account-holder approval. **Owner:** Provider account holder. **Next:** Approve the intended workspace or cloud resource grant, then verify callback, action, reconnect and restart. Observation: Existing connection retained; Reconnect reached real Notion workspace consent. New grant awaits explicit user approval for workspace access. Continued observation: the real UI-triggered notion/notion-fetch result is_error=false, duration 790 ms. Full clean-state/lifecycle acceptance remains unverified. |
-| `slack` (Slack) | Connect entry observed; completion blocked | Not reached | Not verified | Not verified | Not run | Not completed | Windows UI only; other OSes not exercised | **BLOCKED** | Publisher OAuth client is missing; the real UI displays publisher setup pending. **Owner:** Project publisher. **Next:** Provision the official shared OAuth registration and any required review, then repeat the full clean browser journey. Observation: Connect Slack Browser sign-in is not available yet. Browser sign-in is pending publisher setup. No developer account or client registration is required from you. Use your own OAuth client (advanced) Cancel Continue Recheck: live plugin.json includes channels:read, groups:read, im:read, mpim:read, canvases:read and canvases:write; Connect remains publisher-pending. |
+| `slack` (Slack) | Connect entry observed before the 2026-10-05 change; completion blocked | Not reached | Not verified | Not verified | Not run | Not completed | Windows UI only; other OSes not exercised | **BLOCKED** | The shared Slack app registration is pending. On 2026-10-05 the plugin moved from Slack's hosted MCP server (which Slack opens only to Marketplace-listed or internal apps) to the native Slack Web API tool `slack` with eleven user scopes; that configuration has contract tests only and has not been exercised live. **Owner:** Project publisher. **Next:** Finish provisioning the shared Slack app (catalog user scopes, HTTPS redirect through the publisher token broker), then repeat the full clean browser journey with a real read-only `slack` action. Observation (before the change): Connect Slack Browser sign-in is not available yet. Browser sign-in is pending publisher setup. No developer account or client registration is required from you. |
| `linear` (Linear) | Reconnect entry only; existing connection retained | Provider page reached; authorization incomplete | Not verified | Existing state only; new grant not verified | PASS: linear/get_workspace; existing grant | Not completed | Windows UI only; other OSes not exercised | **BLOCKED** | Official provider consent page reached; a new resource access grant awaits explicit account-holder approval. **Owner:** Provider account holder. **Next:** Approve the intended workspace or cloud resource grant, then verify callback, action, reconnect and restart. Observation: Existing connection retained; Reconnect reached official mcp.linear.app authorization page for Personal Jarvis. Continued observation: the real UI-triggered linear/get_workspace result is_error=false, duration 188 ms. Full clean-state/lifecycle acceptance remains unverified. |
| `atlassian` (Atlassian: Jira & Confluence) | Clean connect from Not connected (dev instance, 2026-10-05) | PASS: official Atlassian sign-in and site consent via DCR | PASS | PASS: Connected - Live after tool listing | PASS: atlassian/getVisibleJiraProjects returned the site's project | PASS: disconnect, consent again, Connected; restart kept the grant | Windows only; other OSes not exercised. Needs a Jira or Confluence Cloud site: an account without one gets Atlassian's Access denied page | **PASS** | None. |
| `stripe` (Stripe) | Connect entry observed; completion blocked | Provider page reached; authorization incomplete | Not verified | Not verified | Not run | Not completed | Windows UI only; other OSes not exercised | **BLOCKED** | Provider account sign-in has not been completed. **Owner:** Provider account holder. **Next:** Complete official sign-in and consent, then verify all seven stages with a real read-only plugin action. Observation: Connect opened official dashboard.stripe.com/login. Provider account sign-in required; no manual token or client setup. |
@@ -94,7 +94,7 @@ For closure, complete all independently achievable repairs and replace each rema
The compact catalog is now the direct navigation destination, defaulting to Plugins with Plugins, MCPs, Skills ordering. This UI work does not reduce the plugin acceptance scope. Google Drive, Gmail, Google Calendar, Linear, Notion and Cloudflare each have a genuine successful safe action through Jarvis Chat; all full-plugin results remain BLOCKED until their complete required journeys are proven.
-Slack channel enumeration and Canvas permissions now match the advertised feature set. Only exact old default catalog configurations migrate; custom scopes, clients, redirects, servers and existing grants are preserved. Source: [official Slack MCP scope guide](https://docs.slack.dev/ai/slack-mcp-server/).
+Slack now runs through the native Slack Web API tool instead of Slack's hosted MCP server, because Slack admits only Marketplace-listed or internal apps to that server. Canvas scopes were dropped with it. Only exact old default catalog configurations migrate; custom scopes, clients, redirects, servers and existing grants are preserved. Sources: [Slack MCP server](https://docs.slack.dev/ai/slack-mcp-server/), [PKCE for Slack apps](https://docs.slack.dev/authentication/using-pkce/).
## Compact-window acceptance
diff --git a/docs/marketplace/plugin-e2e-audit.json b/docs/marketplace/plugin-e2e-audit.json
index 34dd9b7bcd..1357fdff41 100644
--- a/docs/marketplace/plugin-e2e-audit.json
+++ b/docs/marketplace/plugin-e2e-audit.json
@@ -204,50 +204,50 @@
{
"plugin_id": "slack",
"result": "BLOCKED",
- "config_fingerprint": "b63622e53686a82209b37ee568201a59eab8feb3334371c770a17939d4e622ff",
+ "config_fingerprint": "ac279f615bdb7c81ca7e489b3a37eb7c39575779b28c1feda06a3f50353194a1",
"initial_state": "connect_attempt",
"evidence": {
"ui": {
"status": "PASS",
- "detail": "Repeated live Plugins UI inspection showed the four channel enumeration scopes and two Canvas scopes in plugin.json; Connect still displays publisher setup pending.",
+ "detail": "A live Plugins UI attempt was observed before 2026-10-05: Connect displayed publisher setup pending. That observation predates the switch to the native Slack Web API tool and the new scope list; the connect dialog for the new configuration has not been re-observed.",
"reference": "docs/marketplace/plugin-auth-audit.md#audit-matrix"
},
"browser": {
"status": "BLOCKED",
- "detail": "Browser completion was not verified in this audit. Publisher OAuth client is missing; the real UI displays publisher setup pending.",
+ "detail": "Browser completion was not verified. The shared Slack app registration is pending, and the native Slack Web API configuration of 2026-10-05 has not been exercised live.",
"reference": "docs/marketplace/plugin-auth-audit.md#audit-matrix"
},
"callback": {
"status": "BLOCKED",
- "detail": "Callback completion was not verified in this audit. Publisher OAuth client is missing; the real UI displays publisher setup pending.",
+ "detail": "Callback completion was not verified. The shared Slack app registration is pending, and the native Slack Web API configuration of 2026-10-05 has not been exercised live.",
"reference": "docs/marketplace/plugin-auth-audit.md#audit-matrix"
},
"connected": {
"status": "BLOCKED",
- "detail": "Connected completion was not verified in this audit. Publisher OAuth client is missing; the real UI displays publisher setup pending.",
+ "detail": "Connected completion was not verified. The shared Slack app registration is pending, and the native Slack Web API configuration of 2026-10-05 has not been exercised live.",
"reference": "docs/marketplace/plugin-auth-audit.md#audit-matrix"
},
"smoke": {
"status": "BLOCKED",
- "detail": "Smoke completion was not verified in this audit. Publisher OAuth client is missing; the real UI displays publisher setup pending.",
+ "detail": "Smoke completion was not verified. The shared Slack app registration is pending, and the native Slack Web API configuration of 2026-10-05 has not been exercised live.",
"reference": "docs/marketplace/plugin-auth-audit.md#audit-matrix"
},
"reconnect": {
"status": "BLOCKED",
- "detail": "Reconnect completion was not verified in this audit. Publisher OAuth client is missing; the real UI displays publisher setup pending.",
+ "detail": "Reconnect completion was not verified. The shared Slack app registration is pending, and the native Slack Web API configuration of 2026-10-05 has not been exercised live.",
"reference": "docs/marketplace/plugin-auth-audit.md#audit-matrix"
},
"restart": {
"status": "BLOCKED",
- "detail": "Restart completion was not verified in this audit. Publisher OAuth client is missing; the real UI displays publisher setup pending.",
+ "detail": "Restart completion was not verified. The shared Slack app registration is pending, and the native Slack Web API configuration of 2026-10-05 has not been exercised live.",
"reference": "docs/marketplace/plugin-auth-audit.md#audit-matrix"
}
},
"blocker": {
- "reason": "Publisher OAuth client is missing; the real UI displays publisher setup pending.",
+ "reason": "The shared Slack app registration is pending, and the Slack plugin moved on 2026-10-05 from Slack's hosted MCP server to the native Slack Web API tool. The new configuration has contract tests only; no live sign-in, connected state, smoke action, reconnect or restart has been observed.",
"owner": "Project publisher",
- "next_action": "Provision the official shared OAuth registration and any required review, then repeat the full clean browser journey.",
- "evidence": "Connect Slack\n\nBrowser sign-in is not available yet.\n\nBrowser sign-in is pending publisher setup. No developer account or client registration is required from you.\n\nUse your own OAuth client (advanced)\nCancel\nContinue"
+ "next_action": "Finish provisioning the shared Slack app (catalog user scopes, HTTPS redirect through the publisher token broker), then run the full clean browser journey with a real read-only slack action (search_messages or read_history), reconnect and restart.",
+ "evidence": "Earlier observation: Connect Slack showed 'Browser sign-in is pending publisher setup. No developer account or client registration is required from you.' The native tool is covered by tests/unit/plugins/tool/test_slack_rest.py only."
}
},
{
diff --git a/jarvis/brain/factory.py b/jarvis/brain/factory.py
index 869554a8b9..53ea3b3a2b 100644
--- a/jarvis/brain/factory.py
+++ b/jarvis/brain/factory.py
@@ -216,6 +216,12 @@ ROUTER_TOOLS = frozenset({
# directly; otherwise a connected YouTube Music is not callable by voice.
# risk_tier "monitor": audible and instantly undone. Never a spawn (AP-5/AP-14).
"youtube_music",
+ # Slack Marketplace plugin (2026-10-05): native REST tool over the Slack Web
+ # API. Slack's hosted MCP server admits only Marketplace-listed or internal
+ # apps, so the plugin carries no MCP server block and must be router-visible
+ # directly. Reads are "safe"; post_message keeps "ask" (echo-confirm).
+ # Never a spawn (AP-5/AP-14).
+ "slack",
# Computer-Use (Wave 1, 2026-05-29): first-class, clearly-described tool to
# drive the user's LIVE desktop (open apps, click, type, scroll, operate
# any GUI). The router previously had no honest desktop path — spawn-worker
diff --git a/jarvis/marketplace/catalog_data.py b/jarvis/marketplace/catalog_data.py
index 1c8d9f96b1..8158dc77cc 100644
--- a/jarvis/marketplace/catalog_data.py
+++ b/jarvis/marketplace/catalog_data.py
@@ -147,9 +147,23 @@ _LEGACY_PAT_AUTH_DIGESTS = {
"stripe": "e19610b1b59a59ffe1e231e8d5adda082437eebb59cec1c2df215470c742dde4",
}
-# Full shipped Slack auth block before channel listing and Canvas permissions.
-# Never widen a user's custom scopes, client, redirect, or server configuration.
-_LEGACY_SLACK_AUTH_DIGEST = "7222ece276d51c75bcdf6f8f0dc28412674950ef21301975b7870a73340c1de2"
+# Full shipped Slack auth blocks of the hosted-MCP era: the first one predates
+# channel listing and Canvas permissions, the second carried the MCP server's
+# granular search scopes. Both pair with the hosted Slack MCP server below,
+# which Slack only opens to Marketplace-listed or internal apps; the plugin now
+# runs the native Web API tool with its own scope set. Never widen a user's
+# custom scopes, client, redirect, or server configuration.
+_LEGACY_SLACK_AUTH_DIGESTS = frozenset(
+ {
+ "7222ece276d51c75bcdf6f8f0dc28412674950ef21301975b7870a73340c1de2",
+ "48825f1d1cbee11f6d8d45e524325cbea053b26fb74a253267ec9d8c590aec15",
+ }
+)
+_LEGACY_SLACK_MCP_SERVER = {
+ "transport": "http",
+ "url": "https://mcp.slack.com/mcp",
+ "auth_header_template": "Authorization: Bearer ${plugin_slack_access_token}",
+}
def _has_obsolete_slack_scopes(plugin: dict, seed_plugin: dict) -> bool:
@@ -159,8 +173,10 @@ def _has_obsolete_slack_scopes(plugin: dict, seed_plugin: dict) -> bool:
digest = hashlib.sha256(
json.dumps(auth, sort_keys=True, separators=(",", ":")).encode("utf-8")
).hexdigest()
- return digest == _LEGACY_SLACK_AUTH_DIGEST and plugin.get("mcp_server") == seed_plugin.get(
- "mcp_server"
+ return digest in _LEGACY_SLACK_AUTH_DIGESTS and plugin.get("mcp_server") in (
+ None,
+ _LEGACY_SLACK_MCP_SERVER,
+ seed_plugin.get("mcp_server"),
)
diff --git a/jarvis/marketplace/connection_verification.py b/jarvis/marketplace/connection_verification.py
index b71285dd8e..2353f3286e 100644
--- a/jarvis/marketplace/connection_verification.py
+++ b/jarvis/marketplace/connection_verification.py
@@ -55,6 +55,9 @@ _NATIVE_PROBES: dict[str, tuple[str, dict[str, str], str]] = {
{"maxResults": "1"},
"kind",
),
+ # auth.test only identifies the token's user; Slack answers failures as
+ # HTTP 200 with ok=false and an "error" key, which the check rejects.
+ "slack": ("https://slack.com/api/auth.test", {}, "user_id"),
"spotify": ("https://api.spotify.com/v1/me", {}, "id"),
"youtube_music": (
"https://www.googleapis.com/youtube/v3/playlists",
@@ -79,7 +82,12 @@ async def _verify_native(spec: PluginSpec, tokens: Tokens) -> None:
)
response.raise_for_status()
payload = response.json()
- if not isinstance(payload, dict) or expected not in payload or payload.get("error"):
+ if (
+ not isinstance(payload, dict)
+ or expected not in payload
+ or payload.get("error")
+ or payload.get("ok") is False
+ ):
raise ConnectionVerificationError(
"The provider returned an unusable resource response."
)
diff --git a/jarvis/marketplace/seed_catalog.json b/jarvis/marketplace/seed_catalog.json
index 52aee6c4f9..8632f720f5 100644
--- a/jarvis/marketplace/seed_catalog.json
+++ b/jarvis/marketplace/seed_catalog.json
@@ -134,7 +134,7 @@
{
"id": "slack",
"display_name": "Slack",
- "description": "Channels, DMs, search and Canvas drafts",
+ "description": "Search, read and post in your channels and DMs",
"category": "Messaging",
"logo_slug": "slack",
"logo_color": "4A154B",
@@ -152,11 +152,7 @@
"scopes": [
"chat:write",
"users:read",
- "users:read.email",
- "search:read.public",
- "search:read.private",
- "search:read.im",
- "search:read.mpim",
+ "search:read",
"channels:history",
"groups:history",
"im:history",
@@ -164,20 +160,14 @@
"channels:read",
"groups:read",
"im:read",
- "mpim:read",
- "canvases:read",
- "canvases:write"
+ "mpim:read"
],
"user_scopes_only": true,
"refresh_supported": true,
"refresh_token_ttl_days": 30
},
- "mcp_server": {
- "transport": "http",
- "url": "https://mcp.slack.com/mcp",
- "auth_header_template": "Authorization: Bearer ${plugin_slack_access_token}"
- },
- "post_install_hint_md": "Slack PKCE apps use user-level scopes only — Jarvis acts as you, not as a bot. If your workspace admin requires approval, the OAuth flow will surface that prompt automatically."
+ "native_tool": "slack",
+ "post_install_hint_md": "Sign in to your Slack workspace in the browser and approve access. Jarvis acts as you with your own permissions, not as a bot: it can search and read the channels and direct messages you belong to, and it posts a message only after you confirm it. Some workspaces require an admin to approve new apps; Slack shows that request during sign-in. The sign-in renews itself; if it lapses after 30 days without use, reconnect here."
},
{
"id": "linear",
diff --git a/jarvis/marketplace/usage_cards/slack.md b/jarvis/marketplace/usage_cards/slack.md
index f211e407b7..e24d0d7042 100644
--- a/jarvis/marketplace/usage_cards/slack.md
+++ b/jarvis/marketplace/usage_cards/slack.md
@@ -2,8 +2,10 @@
plugin_id: slack
keywords: slack, nachricht, message, nachrichten, messages, channel, kanal, kanäle, dm, direktnachricht, direct message, team, posten, post, senden, send, schreiben, write, suchen, search # i18n-allow
---
-Use slack/* tools to read channels, search messages, and send messages or DMs.
-- Jarvis acts as the authenticated user (user-level scopes), not as a bot.
-- Resolve channel names to IDs before posting; never guess an ID.
-- Send messages directly (full autonomy); confirm channel name and message sent afterwards.
-- Search is available across public and private channels the user is a member of.
+Use the slack tool to search, read and post in the user's Slack workspace.
+- Jarvis acts as the signed-in user (user-level scopes), not as a bot, and sees only conversations the user belongs to.
+- `search_messages` takes Slack search syntax (`in:#channel`, `from:@name`, `after:2026-10-01`); answer with channel, author and the gist.
+- Pass a channel as `#name`, an existing DM as `@person`, or an id; the tool resolves names itself and never guesses. Several matching people come back as candidates — ask which one.
+- `read_history` lists newest first; `read_thread` needs the parent message's `thread_ts`.
+- `post_message` needs the user's confirmation before it is sent; afterwards name the channel and repeat what was posted.
+- Starting a brand-new DM is not possible; only existing direct messages can be read or posted to.
diff --git a/jarvis/plugins/tool/slack_rest.py b/jarvis/plugins/tool/slack_rest.py
new file mode 100644
index 0000000000..821588fa29
--- /dev/null
+++ b/jarvis/plugins/tool/slack_rest.py
@@ -0,0 +1,860 @@
+"""slack tool — search, read and post in the user's Slack workspace.
+
+Native REST tool over the Slack Web API, acting as the signed-in person with
+the user token the marketplace PKCE-loopback flow stores (key
+``plugin_slack_tokens``). It replaces the catalog's former binding to Slack's
+hosted MCP server: Slack admits only Marketplace-listed or internal apps to
+that server, and the shared publisher app is a distributed but unlisted app,
+so every end user would have been refused. The Web API accepts the same user
+token, so the tool talks to it directly — the pattern ``drive_rest.py`` and
+``spotify_rest.py`` already follow.
+
+Three properties of the Web API shape everything below:
+
+* **Failures arrive as HTTP 200.** Every method answers ``{"ok": false,
+ "error": "<code>"}``; the status code alone says nothing. Each call checks
+ ``ok`` and turns known codes into fixed sentences. The provider's own text
+ never reaches a log line, the UI or storage (AP-34).
+* **User tokens rotate.** With token rotation (always on for PKCE apps) the
+ access token lives 12 hours and an expired one answers ``token_expired``,
+ not a 401. That code triggers exactly one refresh through the shared
+ refresh path, then the call is retried.
+* **Rate limits are per method.** A 429 carries ``Retry-After`` in seconds. A
+ short wait is absorbed inline once; a longer one is reported, because a
+ voice turn cannot sit out a 30-second penalty.
+
+Per-action risk tiers: every read is ``safe``; ``post_message`` speaks for the
+user in front of other people, so it keeps the ``ask`` tier and the two-turn
+echo-confirm. A direct gated action, never a spawn (AP-5/AP-14).
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import re
+import time
+from collections.abc import Awaitable, Callable
+from typing import Any
+
+from jarvis.core.protocols import ExecutionContext, ToolResult
+
+log = logging.getLogger(__name__)
+
+_API = "https://slack.com/api"
+
+_NOT_CONNECTED = "Slack is not connected — connect it in the Plugins view."
+_NEEDS_RECONNECT = (
+ "Slack rejected the stored authorization and it could not be renewed — "
+ "reconnect Slack in the Plugins view."
+)
+_MISSING_SCOPE = (
+ "Slack has not granted the permission this needs. Reconnect Slack in the "
+ "Plugins view to grant it."
+)
+_GENERIC_FAILURE = "Slack could not complete the request. Try again in a moment."
+
+# Fixed explanations for the Slack error codes a person can act on. Codes not
+# listed fall back to _GENERIC_FAILURE; the provider's text is never echoed.
+_ERROR_MESSAGES: dict[str, str] = {
+ "not_authed": _NEEDS_RECONNECT,
+ "invalid_auth": _NEEDS_RECONNECT,
+ "token_expired": _NEEDS_RECONNECT,
+ "token_revoked": _NEEDS_RECONNECT,
+ "account_inactive": _NEEDS_RECONNECT,
+ "missing_scope": _MISSING_SCOPE,
+ "no_permission": _MISSING_SCOPE,
+ "channel_not_found": (
+ "Slack could not find that conversation, or the user is not a member of it."
+ ),
+ "not_in_channel": "The user is not a member of that channel, so nothing can be posted there.",
+ "is_archived": "That channel is archived, so nothing can be posted there.",
+ "msg_too_long": "That message is too long for Slack.",
+ "no_text": "The message is empty — say what should be posted.",
+ "thread_not_found": "Slack could not find that thread.",
+ "message_not_found": "Slack could not find that message.",
+ "user_not_found": "Slack could not find that person.",
+ "invalid_cursor": "That page marker has expired — start the listing again.",
+ "restricted_action": "The workspace's settings do not allow this action.",
+ "team_access_not_granted": "The workspace has not granted access to this app.",
+ "ekm_access_denied": "The workspace's administrators have blocked access to this content.",
+}
+
+# Codes a single token refresh can heal (rotation expired the access token).
+_REFRESHABLE = frozenset({"token_expired", "invalid_auth", "not_authed"})
+
+# Absorb a rate limit inline only when it fits the voice tool budget.
+_MAX_INLINE_RETRY_S = 2.0
+
+_ID_RE = re.compile(r"^[CGD][A-Z0-9]{6,}$")
+_USER_ID_RE = re.compile(r"^[UW][A-Z0-9]{6,}$")
+
+_ALL_TYPES = "public_channel,private_channel,mpim,im"
+_NAMED_TYPES = "public_channel,private_channel,mpim"
+_PAGE_SIZE = 200
+_MAX_PAGES = 10
+_LIST_DEFAULT = 100
+_LIST_MAX = 1000
+_TEXT_CAP = 4_000
+_POST_MAX_CHARS = 40_000
+_USER_LOOKUPS_PER_CALL = 15
+_DIRECTORY_TTL_S = 300.0
+
+
+class SlackApiError(Exception):
+ """A Slack ``ok: false`` answer or HTTP refusal, reduced to its code.
+
+ Only the machine code is kept. The string form never contains provider
+ text, so an accidental ``str(exc)`` cannot leak a response body."""
+
+ def __init__(self, code: str, *, retry_after: float | None = None) -> None:
+ super().__init__(code)
+ self.code = code
+ self.retry_after = retry_after
+
+
+class _ToolError(Exception):
+ """A failure whose message this module wrote itself (safe to show)."""
+
+ def __init__(self, message: str, *, candidates: list[dict[str, Any]] | None = None) -> None:
+ super().__init__(message)
+ self.message = message
+ self.candidates = candidates
+
+
+def _default_token_provider() -> str | None:
+ from jarvis.marketplace.token_store import TokenStore
+
+ tokens = TokenStore().load("slack")
+ return tokens.access if tokens is not None else None
+
+
+async def _default_refresher(observed_access_token: str | None = None) -> bool:
+ """Refresh the stored Slack token in place. Returns True on success.
+
+ On an un-healable failure (revoked grant, a refresh token past Slack's
+ 30-day PKCE ceiling, a placeholder client) it flags ``needs_reauth`` so
+ the Plugins view offers Reconnect instead of a green dot that lies.
+ Best-effort: any error returns False and never raises into the tool."""
+ from jarvis.marketplace.connect_helpers import build_handler_from_catalog
+ from jarvis.marketplace.refresh_scheduler import refresh_plugin_token
+ from jarvis.marketplace.token_store import TokenStore
+
+ attempt = await refresh_plugin_token(
+ "slack",
+ TokenStore(),
+ build_handler_from_catalog,
+ force=True,
+ observed_access_token=observed_access_token,
+ )
+ return attempt.usable
+
+
+def _retry_after_seconds(headers: Any) -> float:
+ try:
+ return max(0.0, float(headers.get("Retry-After", "")))
+ except (TypeError, ValueError):
+ return 30.0 # Slack always sends it; an unreadable value means "not now"
+
+
+def _cap(text: Any) -> str:
+ value = str(text or "")
+ if len(value) > _TEXT_CAP:
+ return value[:_TEXT_CAP] + "… [truncated]"
+ return value
+
+
+def _conversation_kind(conv: dict[str, Any]) -> str:
+ if conv.get("is_im"):
+ return "dm"
+ if conv.get("is_mpim"):
+ return "group_dm"
+ if conv.get("is_private") or conv.get("is_group"):
+ return "private_channel"
+ return "channel"
+
+
+def _slim_conversation(conv: dict[str, Any]) -> dict[str, Any]:
+ out: dict[str, Any] = {
+ "id": conv.get("id"),
+ "name": conv.get("name"),
+ "kind": _conversation_kind(conv),
+ }
+ if conv.get("is_im"):
+ out["user"] = conv.get("user")
+ else:
+ out["is_member"] = bool(conv.get("is_member"))
+ if isinstance(conv.get("num_members"), int):
+ out["num_members"] = conv["num_members"]
+ return out
+
+
+def _slim_message(msg: dict[str, Any]) -> dict[str, Any]:
+ out: dict[str, Any] = {
+ "ts": msg.get("ts"),
+ "user": msg.get("user") or msg.get("bot_id"),
+ "text": _cap(msg.get("text")),
+ }
+ if msg.get("thread_ts"):
+ out["thread_ts"] = msg["thread_ts"]
+ if isinstance(msg.get("reply_count"), int):
+ out["reply_count"] = msg["reply_count"]
+ if msg.get("files"):
+ out["files"] = [f.get("name") for f in msg["files"] if isinstance(f, dict)]
+ return out
+
+
+def _slim_user(user: dict[str, Any]) -> dict[str, Any]:
+ profile = user.get("profile") if isinstance(user.get("profile"), dict) else {}
+ return {
+ "id": user.get("id"),
+ "name": user.get("name"),
+ "real_name": user.get("real_name") or profile.get("real_name"),
+ "display_name": profile.get("display_name") or None,
+ "title": profile.get("title") or None,
+ "tz": user.get("tz"),
+ "is_bot": bool(user.get("is_bot")),
+ "deleted": bool(user.get("deleted")),
+ }
+
+
+def _display_name(user: dict[str, Any]) -> str:
+ profile = user.get("profile") if isinstance(user.get("profile"), dict) else {}
+ return str(
+ profile.get("display_name")
+ or user.get("real_name")
+ or profile.get("real_name")
+ or user.get("name")
+ or user.get("id")
+ or ""
+ )
+
+
+def _user_matches(user: dict[str, Any], needle: str) -> bool:
+ profile = user.get("profile") if isinstance(user.get("profile"), dict) else {}
+ fields = (
+ user.get("name"),
+ user.get("real_name"),
+ profile.get("real_name"),
+ profile.get("display_name"),
+ )
+ return any(needle in str(f).lower() for f in fields if f)
+
+
+def _user_exact(user: dict[str, Any], needle: str) -> bool:
+ profile = user.get("profile") if isinstance(user.get("profile"), dict) else {}
+ fields = (
+ user.get("name"),
+ user.get("real_name"),
+ profile.get("real_name"),
+ profile.get("display_name"),
+ )
+ return any(str(f).lower() == needle for f in fields if f)
+
+
+class SlackRestTool:
+ name: str = "slack"
+ # Static tier is the conservative one; reads are downgraded per call.
+ risk_tier: str = "ask"
+ description: str = (
+ "Search, read and post in the user's connected Slack workspace, acting "
+ "as the user. Use for 'what did Anna say in Slack', 'search Slack for "
+ "the release date', 'what's new in #general', 'read that thread', "
+ "'post in #team that I'm late'. Actions: search_messages (query, Slack "
+ "search syntax works: in:#channel from:@name), list_conversations "
+ "(channels, private channels, group DMs and DMs the user belongs to), "
+ "read_history (channel by #name, @person for an existing DM, or id), "
+ "read_thread (channel + thread_ts), get_user (user id), find_users "
+ "(name), post_message (channel + text, optional thread_ts to reply in "
+ "a thread). Requires the Slack plugin to be connected in the Plugins "
+ "view. Posting needs the user's confirmation."
+ )
+ schema: dict[str, Any] = {
+ "type": "object",
+ "properties": {
+ "action": {
+ "type": "string",
+ "enum": [
+ "search_messages",
+ "list_conversations",
+ "read_history",
+ "read_thread",
+ "get_user",
+ "find_users",
+ "post_message",
+ ],
+ "default": "search_messages",
+ },
+ "query": {
+ "type": "string",
+ "description": "search text (search_messages) or a person's name (find_users)",
+ },
+ "channel": {
+ "type": "string",
+ "description": (
+ "conversation: '#name', '@person' for an existing DM, or a "
+ "Slack id like C0123ABCD"
+ ),
+ },
+ "thread_ts": {
+ "type": "string",
+ "description": "parent message ts (read_thread; post_message to reply in a thread)",
+ },
+ "user": {"type": "string", "description": "Slack user id (get_user)"},
+ "text": {"type": "string", "description": "message text (post_message)"},
+ "types": {
+ "type": "string",
+ "description": (
+ "list_conversations filter, comma-separated from "
+ "public_channel, private_channel, mpim, im (default all)"
+ ),
+ },
+ "limit": {"type": "integer", "description": "how many results to return"},
+ "cursor": {
+ "type": "string",
+ "description": "next_cursor from a previous answer, to continue a listing",
+ },
+ },
+ "required": ["action"],
+ }
+
+ def __init__(
+ self,
+ access_token_provider: Callable[[], str | None] | None = None,
+ transport: Any | None = None,
+ token_refresher: Callable[[], Awaitable[bool]] | None = None,
+ sleep: Callable[[float], Awaitable[None]] | None = None,
+ ) -> None:
+ from ._http_pool import HttpClientPool
+
+ self._token_provider = access_token_provider or _default_token_provider
+ self._refresher = token_refresher
+ self._sleep = sleep or asyncio.sleep
+ # Keep-alive pool: resolving a channel name and then reading it is two
+ # calls in a row, so one warm TLS connection beats two handshakes.
+ self._pool = HttpClientPool(transport=transport)
+ self._user_names: dict[str, str] = {}
+ self._directory: list[dict[str, Any]] | None = None
+ self._directory_at = 0.0
+
+ # -- transport ----------------------------------------------------------
+
+ def _bearer(self) -> dict[str, str] | None:
+ token = self._token_provider()
+ if not token:
+ return None
+ return {"Authorization": f"Bearer {token}", "User-Agent": "Personal-Jarvis/1.0"}
+
+ async def _api(
+ self,
+ method: str,
+ headers: dict[str, str],
+ *,
+ params: dict[str, Any] | None = None,
+ json_body: dict[str, Any] | None = None,
+ ) -> dict[str, Any]:
+ """One Web API call. Returns the payload of an ``ok: true`` answer and
+ raises :class:`SlackApiError` for everything else."""
+ client = self._pool.client()
+ url = f"{_API}/{method}"
+ for attempt in range(2):
+ if json_body is not None:
+ resp = await client.post(
+ url,
+ json=json_body,
+ headers={**headers, "Content-Type": "application/json; charset=utf-8"},
+ )
+ else:
+ resp = await client.get(url, params=params or {}, headers=headers)
+ if resp.status_code == 429:
+ wait = _retry_after_seconds(resp.headers)
+ if attempt == 0 and wait <= _MAX_INLINE_RETRY_S:
+ # A 429 means nothing was done, so a retry cannot double-post.
+ await self._sleep(wait)
+ continue
+ raise SlackApiError("ratelimited", retry_after=wait)
+ if resp.status_code == 401:
+ raise SlackApiError("invalid_auth")
+ if resp.status_code >= 400:
+ raise SlackApiError(f"http_{resp.status_code}")
+ try:
+ payload = resp.json()
+ except ValueError:
+ raise SlackApiError("invalid_response") from None
+ if not isinstance(payload, dict):
+ raise SlackApiError("invalid_response")
+ if payload.get("ok") is not True:
+ raise SlackApiError(str(payload.get("error") or "unknown"))
+ return payload
+ raise SlackApiError("ratelimited", retry_after=_MAX_INLINE_RETRY_S)
+
+ async def _with_auth_retry(
+ self, do_call: Callable[[dict[str, str]], Awaitable[Any]]
+ ) -> Any:
+ """Run an authenticated action; on an expired token refresh once and
+ retry. With rotation the access token lives 12 hours, so this path is
+ ordinary rather than exceptional."""
+ headers = self._bearer()
+ if headers is None:
+ return {"error": _NOT_CONNECTED}
+ try:
+ return await do_call(headers)
+ except SlackApiError as exc:
+ if exc.code not in _REFRESHABLE:
+ raise
+ observed_token = headers["Authorization"].removeprefix("Bearer ")
+ try:
+ if self._refresher is None:
+ refreshed = bool(await _default_refresher(observed_token))
+ else:
+ refreshed = bool(await self._refresher())
+ except Exception: # noqa: BLE001 — refresher must never crash the tool
+ log.warning("slack token refresh raised; asking the user to reconnect")
+ refreshed = False
+ if not refreshed:
+ return {"error": _NEEDS_RECONNECT}
+ headers = self._bearer()
+ if headers is None:
+ return {"error": _NEEDS_RECONNECT}
+ return await do_call(headers)
+
+ async def _paged(
+ self,
+ method: str,
+ headers: dict[str, str],
+ key: str,
+ params: dict[str, Any],
+ *,
+ want: int,
+ cursor: str = "",
+ stop: Callable[[list[dict[str, Any]]], bool] | None = None,
+ ) -> tuple[list[dict[str, Any]], str]:
+ """Follow ``response_metadata.next_cursor`` until ``want`` items, the
+ last page, ``stop`` says enough, or the page cap. Returns the items and
+ the cursor to continue from ("" when exhausted)."""
+ items: list[dict[str, Any]] = []
+ next_cursor = cursor
+ for _ in range(_MAX_PAGES):
+ page_params = {**params, "limit": min(_PAGE_SIZE, max(1, want - len(items)))}
+ if next_cursor:
+ page_params["cursor"] = next_cursor
+ payload = await self._api(method, headers, params=page_params)
+ batch = [i for i in (payload.get(key) or []) if isinstance(i, dict)]
+ items.extend(batch)
+ meta = payload.get("response_metadata")
+ next_cursor = str(meta.get("next_cursor") or "") if isinstance(meta, dict) else ""
+ # `stop` sees every page, including the last one.
+ satisfied = stop(batch) if stop is not None else False
+ if satisfied or not next_cursor or len(items) >= want:
+ break
+ return items[:want], next_cursor
+
+ # -- lookups ------------------------------------------------------------
+
+ async def _users(self, headers: dict[str, str]) -> list[dict[str, Any]]:
+ """The workspace directory, cached for a few minutes per tool."""
+ now = time.monotonic()
+ if self._directory is not None and now - self._directory_at < _DIRECTORY_TTL_S:
+ return self._directory
+ users, _ = await self._paged(
+ "users.list", headers, "members", {}, want=_PAGE_SIZE * _MAX_PAGES
+ )
+ self._directory = users
+ self._directory_at = now
+ for user in users:
+ if user.get("id"):
+ self._user_names[str(user["id"])] = _display_name(user)
+ return users
+
+ async def _names_for(self, ids: list[str], headers: dict[str, str]) -> dict[str, str]:
+ """Display names for user ids, from cache or ``users.info``.
+
+ Bounded per call. A lookup that fails leaves the raw id in place: the
+ answer is still correct, only less friendly, so it is logged and the
+ read carries on."""
+ lookups = 0
+ for uid in dict.fromkeys(i for i in ids if i and _USER_ID_RE.match(i)):
+ if uid in self._user_names or lookups >= _USER_LOOKUPS_PER_CALL:
+ continue
+ lookups += 1
+ try:
+ payload = await self._api("users.info", headers, params={"user": uid})
+ except SlackApiError as exc:
+ if exc.code in _REFRESHABLE:
+ raise
+ log.debug("slack users.info failed (%s); keeping the raw id", exc.code)
+ continue
+ user = payload.get("user")
+ if isinstance(user, dict):
+ self._user_names[uid] = _display_name(user)
+ return {uid: self._user_names[uid] for uid in ids if uid in self._user_names}
+
+ async def _with_names(
+ self, messages: list[dict[str, Any]], headers: dict[str, str]
+ ) -> list[dict[str, Any]]:
+ names = await self._names_for([str(m.get("user") or "") for m in messages], headers)
+ for message in messages:
+ uid = str(message.get("user") or "")
+ if uid in names:
+ message["user_name"] = names[uid]
+ return messages
+
+ async def _find_user(self, needle: str, headers: dict[str, str]) -> dict[str, Any]:
+ users = [u for u in await self._users(headers) if not u.get("deleted")]
+ exact = [u for u in users if _user_exact(u, needle)]
+ hits = exact or [u for u in users if _user_matches(u, needle)]
+ if not hits:
+ raise _ToolError(f"Slack has nobody called {needle!r}.")
+ if len(hits) > 1:
+ raise _ToolError(
+ f"Several people match {needle!r} — say which one.",
+ candidates=[_slim_user(u) for u in hits[:10]],
+ )
+ return hits[0]
+
+ async def _resolve_channel(self, channel: str, headers: dict[str, str]) -> str:
+ """Turn '#name', '@person', a user id or a conversation id into a
+ conversation id. Never guesses: no match is an error, several are a
+ question back to the user."""
+ raw = channel.strip()
+ if not raw:
+ raise _ToolError("Say which channel or person.")
+ if _ID_RE.match(raw):
+ return raw
+ if raw.startswith("@") or _USER_ID_RE.match(raw):
+ return await self._resolve_dm(raw, headers)
+ name = raw.lstrip("#").strip().lower()
+ found: list[dict[str, Any]] = []
+
+ def _stop(batch: list[dict[str, Any]]) -> bool:
+ found.extend(
+ c
+ for c in batch
+ if str(c.get("name") or "").lower() == name
+ or str(c.get("name_normalized") or "").lower() == name
+ )
+ return bool(found)
+
+ await self._paged(
+ "conversations.list",
+ headers,
+ "channels",
+ {"types": _NAMED_TYPES, "exclude_archived": "true"},
+ want=_PAGE_SIZE * _MAX_PAGES,
+ stop=_stop,
+ )
+ if not found:
+ raise _ToolError(
+ f"Slack has no channel called #{name} that the user belongs to."
+ )
+ return str(found[0]["id"])
+
+ async def _resolve_dm(self, raw: str, headers: dict[str, str]) -> str:
+ target = raw.lstrip("@").strip()
+ if _USER_ID_RE.match(target):
+ uid = target
+ label = target
+ else:
+ user = await self._find_user(target.lower(), headers)
+ uid = str(user.get("id"))
+ label = _display_name(user)
+ found: list[str] = []
+
+ def _stop(batch: list[dict[str, Any]]) -> bool:
+ found.extend(str(c["id"]) for c in batch if c.get("user") == uid and c.get("id"))
+ return bool(found)
+
+ await self._paged(
+ "conversations.list",
+ headers,
+ "channels",
+ {"types": "im"},
+ want=_PAGE_SIZE * _MAX_PAGES,
+ stop=_stop,
+ )
+ if not found:
+ raise _ToolError(
+ f"There is no direct message with {label} yet. Slack only lets "
+ "Jarvis use direct messages that already exist."
+ )
+ return found[0]
+
+ # -- public actions (also directly unit-testable) -----------------------
+
+ async def search_messages(
+ self, *, query: str, limit: int = 10, page: int = 1
+ ) -> dict[str, Any]:
+ count = max(1, min(int(limit), 50))
+
+ async def _do(headers: dict[str, str]) -> dict[str, Any]:
+ payload = await self._api(
+ "search.messages",
+ headers,
+ params={
+ "query": query,
+ "count": count,
+ "page": max(1, int(page)),
+ "sort": "timestamp",
+ "sort_dir": "desc",
+ },
+ )
+ block = payload.get("messages") if isinstance(payload.get("messages"), dict) else {}
+ matches = [m for m in (block.get("matches") or []) if isinstance(m, dict)]
+ results = []
+ for match in matches:
+ chan = match.get("channel") if isinstance(match.get("channel"), dict) else {}
+ results.append(
+ {
+ "channel_id": chan.get("id"),
+ "channel": chan.get("name"),
+ "user": match.get("user"),
+ "user_name": match.get("username"),
+ "text": _cap(match.get("text")),
+ "ts": match.get("ts"),
+ "permalink": match.get("permalink"),
+ }
+ )
+ paging = block.get("paging") if isinstance(block.get("paging"), dict) else {}
+ return {
+ "query": query,
+ "total": block.get("total", len(results)),
+ "page": paging.get("page", page),
+ "pages": paging.get("pages"),
+ "messages": results,
+ }
+
+ return await self._with_auth_retry(_do)
+
+ async def list_conversations(
+ self, *, types: str = "", limit: int = _LIST_DEFAULT, cursor: str = ""
+ ) -> dict[str, Any]:
+ allowed = {"public_channel", "private_channel", "mpim", "im"}
+ wanted = [t.strip() for t in (types or _ALL_TYPES).split(",") if t.strip() in allowed]
+ want = max(1, min(int(limit), _LIST_MAX))
+
+ async def _do(headers: dict[str, str]) -> dict[str, Any]:
+ convs, next_cursor = await self._paged(
+ "conversations.list",
+ headers,
+ "channels",
+ {"types": ",".join(wanted or [_ALL_TYPES]), "exclude_archived": "true"},
+ want=want,
+ cursor=cursor,
+ )
+ slim = [_slim_conversation(c) for c in convs]
+ dm_users = [str(c.get("user") or "") for c in slim if c["kind"] == "dm"]
+ names = await self._names_for(dm_users, headers)
+ for conv in slim:
+ if conv["kind"] == "dm" and conv.get("user") in names:
+ conv["name"] = names[conv["user"]]
+ out: dict[str, Any] = {"conversations": slim, "count": len(slim)}
+ if next_cursor:
+ out["next_cursor"] = next_cursor
+ return out
+
+ return await self._with_auth_retry(_do)
+
+ async def read_history(
+ self, *, channel: str, limit: int = 20, cursor: str = ""
+ ) -> dict[str, Any]:
+ count = max(1, min(int(limit), 100))
+
+ async def _do(headers: dict[str, str]) -> dict[str, Any]:
+ channel_id = await self._resolve_channel(channel, headers)
+ params: dict[str, Any] = {"channel": channel_id, "limit": count}
+ if cursor:
+ params["cursor"] = cursor
+ payload = await self._api("conversations.history", headers, params=params)
+ raw = [m for m in (payload.get("messages") or []) if isinstance(m, dict)]
+ messages = await self._with_names([_slim_message(m) for m in raw], headers)
+ meta = payload.get("response_metadata")
+ out: dict[str, Any] = {
+ "channel_id": channel_id,
+ "order": "newest first",
+ "messages": messages,
+ }
+ next_cursor = meta.get("next_cursor") if isinstance(meta, dict) else ""
+ if payload.get("has_more") and next_cursor:
+ out["next_cursor"] = next_cursor
+ return out
+
+ return await self._with_auth_retry(_do)
+
+ async def read_thread(
+ self, *, channel: str, thread_ts: str, limit: int = 50, cursor: str = ""
+ ) -> dict[str, Any]:
+ count = max(1, min(int(limit), 200))
+
+ async def _do(headers: dict[str, str]) -> dict[str, Any]:
+ channel_id = await self._resolve_channel(channel, headers)
+ params: dict[str, Any] = {"channel": channel_id, "ts": thread_ts, "limit": count}
+ if cursor:
+ params["cursor"] = cursor
+ payload = await self._api("conversations.replies", headers, params=params)
+ raw = [m for m in (payload.get("messages") or []) if isinstance(m, dict)]
+ messages = await self._with_names([_slim_message(m) for m in raw], headers)
+ meta = payload.get("response_metadata")
+ out: dict[str, Any] = {
+ "channel_id": channel_id,
+ "thread_ts": thread_ts,
+ "order": "oldest first",
+ "messages": messages,
+ }
+ next_cursor = meta.get("next_cursor") if isinstance(meta, dict) else ""
+ if payload.get("has_more") and next_cursor:
+ out["next_cursor"] = next_cursor
+ return out
+
+ return await self._with_auth_retry(_do)
+
+ async def get_user(self, *, user: str) -> dict[str, Any]:
+ async def _do(headers: dict[str, str]) -> dict[str, Any]:
+ payload = await self._api("users.info", headers, params={"user": user.strip()})
+ raw = payload.get("user")
+ if not isinstance(raw, dict):
+ raise SlackApiError("user_not_found")
+ return _slim_user(raw)
+
+ return await self._with_auth_retry(_do)
+
+ async def find_users(self, *, query: str, limit: int = 10) -> dict[str, Any]:
+ needle = query.strip().lstrip("@").lower()
+
+ async def _do(headers: dict[str, str]) -> dict[str, Any]:
+ users = [u for u in await self._users(headers) if not u.get("deleted")]
+ hits = [u for u in users if _user_matches(u, needle)]
+ capped = hits[: max(1, min(int(limit), 50))]
+ return {"query": query, "users": [_slim_user(u) for u in capped]}
+
+ return await self._with_auth_retry(_do)
+
+ async def post_message(
+ self, *, channel: str, text: str, thread_ts: str = ""
+ ) -> dict[str, Any]:
+ if not text.strip():
+ return {"error": _ERROR_MESSAGES["no_text"]}
+ if len(text) > _POST_MAX_CHARS:
+ return {"error": _ERROR_MESSAGES["msg_too_long"]}
+
+ async def _do(headers: dict[str, str]) -> dict[str, Any]:
+ channel_id = await self._resolve_channel(channel, headers)
+ body: dict[str, Any] = {"channel": channel_id, "text": text}
+ if thread_ts.strip():
+ body["thread_ts"] = thread_ts.strip()
+ payload = await self._api("chat.postMessage", headers, json_body=body)
+ return {
+ "posted": True,
+ "channel_id": payload.get("channel") or channel_id,
+ "ts": payload.get("ts"),
+ "thread_ts": body.get("thread_ts"),
+ }
+
+ return await self._with_auth_retry(_do)
+
+ # -- Tool protocol ------------------------------------------------------
+
+ def risk_tier_for_args(self, args: dict[str, Any]) -> str:
+ """Per-action risk tier (consulted by ``RiskTierEvaluator``).
+
+ Reads are ``safe``. ``post_message`` speaks for the user in front of
+ colleagues and cannot be taken back unnoticed, so it keeps ``ask`` and
+ the two-turn echo-confirm. An unknown action stays ``ask``."""
+ action = str(args.get("action") or "search_messages").strip()
+ if action in (
+ "search_messages",
+ "list_conversations",
+ "read_history",
+ "read_thread",
+ "get_user",
+ "find_users",
+ ):
+ return "safe"
+ return "ask"
+
+ async def execute(self, args: dict[str, Any], ctx: ExecutionContext) -> ToolResult:
+ action = str(args.get("action") or "search_messages").strip()
+ query = str(args.get("query") or "").strip()
+ channel = str(args.get("channel") or "").strip()
+ cursor = str(args.get("cursor") or "").strip()
+ thread_ts = str(args.get("thread_ts") or "").strip()
+ try:
+ limit = int(args["limit"]) if args.get("limit") is not None else None
+ except (TypeError, ValueError):
+ return ToolResult(success=False, output=None, error="limit must be a number")
+ try:
+ if action == "search_messages":
+ if not query:
+ return _missing("search_messages needs a query")
+ out = await self.search_messages(query=query, limit=limit or 10)
+ elif action == "list_conversations":
+ out = await self.list_conversations(
+ types=str(args.get("types") or ""),
+ limit=limit or _LIST_DEFAULT,
+ cursor=cursor,
+ )
+ elif action == "read_history":
+ if not channel:
+ return _missing("read_history needs a channel")
+ out = await self.read_history(channel=channel, limit=limit or 20, cursor=cursor)
+ elif action == "read_thread":
+ if not channel or not thread_ts:
+ return _missing("read_thread needs a channel and thread_ts")
+ out = await self.read_thread(
+ channel=channel, thread_ts=thread_ts, limit=limit or 50, cursor=cursor
+ )
+ elif action == "get_user":
+ user = str(args.get("user") or "").strip()
+ if not user:
+ return _missing("get_user needs a user id")
+ out = await self.get_user(user=user)
+ elif action == "find_users":
+ if not query:
+ return _missing("find_users needs a query")
+ out = await self.find_users(query=query, limit=limit or 10)
+ elif action == "post_message":
+ if not channel:
+ return _missing("post_message needs a channel")
+ out = await self.post_message(
+ channel=channel, text=str(args.get("text") or ""), thread_ts=thread_ts
+ )
+ else:
+ return ToolResult(success=False, output=None, error=f"unknown action {action!r}")
+ except _ToolError as exc:
+ if exc.candidates:
+ return ToolResult(
+ success=False,
+ output={"candidates": exc.candidates},
+ error=exc.message,
+ )
+ return ToolResult(success=False, output=None, error=exc.message)
+ except Exception as exc: # noqa: BLE001 — every failure reaches the model via _explain()
+ return ToolResult(success=False, output=None, error=self._explain(exc, action))
+
+ if isinstance(out, dict) and out.get("error"):
+ return ToolResult(success=False, output=None, error=out["error"])
+ return ToolResult(success=True, output=out)
+
+ @staticmethod
+ def _explain(exc: Exception, action: str) -> str:
+ """Turn a transport or API failure into a fixed sentence a person can
+ act on. Logs only the action and the machine code, never a body."""
+ import httpx
+
+ if isinstance(exc, SlackApiError):
+ log.info("slack %s failed: %s", action, exc.code)
+ if exc.code == "ratelimited":
+ wait = int(exc.retry_after or 30)
+ return f"Slack is rate-limiting these requests — try again in {wait} seconds."
+ if exc.code.startswith("http_5"):
+ return "Slack is having trouble right now. Try again shortly."
+ return _ERROR_MESSAGES.get(exc.code, _GENERIC_FAILURE)
+ if isinstance(exc, httpx.ConnectError | httpx.ConnectTimeout):
+ return "Could not reach Slack. Check this machine's internet connection."
+ if isinstance(exc, httpx.TimeoutException):
+ return "Slack did not answer in time. Try again in a moment."
+ log.warning("slack %s failed with %s", action, type(exc).__name__)
+ return _GENERIC_FAILURE
+
+
+def _missing(message: str) -> ToolResult:
+ return ToolResult(success=False, output=None, error=message)
diff --git a/pyproject.toml b/pyproject.toml
index cc8f797298..846b658219 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -691,6 +691,14 @@ spotify = "jarvis.plugins.tool.spotify_rest:SpotifyRestTool"
# (AP-5/AP-14). Entry-point name matches the catalog native_tool + token-store
# key "youtube_music".
youtube_music = "jarvis.plugins.tool.youtube_music_rest:YouTubeMusicRestTool"
+# Slack (marketplace plugin, 2026-10-05) — search/read/post over the Slack Web
+# API with the marketplace-stored user token. Native rather than Slack's hosted
+# MCP server: Slack admits only Marketplace-listed or internal apps to that
+# server, and the shared publisher app is a distributed but unlisted app.
+# Router-tier; reads are "safe", posting keeps "ask" (echo-confirm). Never a
+# spawn (AP-5/AP-14). Entry-point name matches the catalog native_tool +
+# token-store key "slack".
+slack = "jarvis.plugins.tool.slack_rest:SlackRestTool"
screen-snapshot = "jarvis.plugins.tool.screen_snapshot:ScreenSnapshotTool"
move-mouse = "jarvis.plugins.tool.move_mouse:MoveMouseTool"
switch-window = "jarvis.plugins.tool.switch_window:SwitchWindowTool"
diff --git a/tests/unit/brain/test_routing.py b/tests/unit/brain/test_routing.py
index 7c4e41a646..b0a3b46019 100644
--- a/tests/unit/brain/test_routing.py
+++ b/tests/unit/brain/test_routing.py
@@ -1927,6 +1927,11 @@ def test_router_tools_is_pure_dispatcher_set() -> None:
# must be router-visible directly. risk_tier "monitor". Never a
# spawn (AP-5/AP-14).
"youtube_music",
+ # Slack Marketplace plugin (2026-10-05): native REST tool over the
+ # Slack Web API — the hosted Slack MCP server admits only
+ # Marketplace-listed or internal apps. Reads safe, posting ask.
+ # Never a spawn (AP-5/AP-14).
+ "slack",
# Computer-Use (Wave 1, 2026-05-29): first-class tool to drive the
# live desktop. Router-tier only — a direct safe-gated action (the
# loop gates each action via ToolExecutor, ADR-0008), never a spawn,
diff --git a/tests/unit/marketplace/test_catalog_seed.py b/tests/unit/marketplace/test_catalog_seed.py
index 28343b1ece..4de46779a3 100644
--- a/tests/unit/marketplace/test_catalog_seed.py
+++ b/tests/unit/marketplace/test_catalog_seed.py
@@ -100,24 +100,58 @@ def test_override_keeps_connection_details_but_not_presentation(monkeypatch, tmp
clear_cache()
-def test_slack_scopes_cover_channel_listing_and_canvas_drafts() -> None:
+def test_slack_runs_the_native_web_api_tool() -> None:
+ """Slack's hosted MCP server admits only Marketplace-listed or internal
+ apps, so the shared (unlisted) app runs the native Web API tool."""
slack = _seed().by_id("slack")
assert slack is not None
- assert {
- "channels:read",
- "groups:read",
- "im:read",
- "mpim:read",
- "canvases:read",
- "canvases:write",
- } <= set(slack.auth.scopes)
-
-
+ assert slack.native_tool == "slack"
+ assert slack.mcp_server is None
+ assert {"search:read", "channels:read", "groups:read", "im:read", "mpim:read"} <= set(
+ slack.auth.scopes
+ )
+ assert not {"canvases:read", "canvases:write"} & set(slack.auth.scopes)
+
+
+_FIRST_SLACK_SCOPES = [
+ "chat:write",
+ "users:read",
+ "users:read.email",
+ "search:read.public",
+ "search:read.private",
+ "search:read.im",
+ "search:read.mpim",
+ "channels:history",
+ "groups:history",
+ "im:history",
+ "mpim:history",
+]
+_SECOND_SLACK_SCOPES = [
+ *_FIRST_SLACK_SCOPES,
+ "channels:read",
+ "groups:read",
+ "im:read",
+ "mpim:read",
+ "canvases:read",
+ "canvases:write",
+]
+_HOSTED_SLACK_MCP = {
+ "transport": "http",
+ "url": "https://mcp.slack.com/mcp",
+ "auth_header_template": "Authorization: Bearer ${plugin_slack_access_token}",
+}
+
+
[email protected]("legacy", [_FIRST_SLACK_SCOPES, _SECOND_SLACK_SCOPES])
@pytest.mark.parametrize("custom", [None, "scopes", "client", "redirect", "server"])
-def test_slack_scope_upgrade_preserves_custom_auth_and_disk(monkeypatch, tmp_path, custom) -> None:
+def test_slack_scope_upgrade_preserves_custom_auth_and_disk(
+ monkeypatch, tmp_path, custom, legacy
+) -> None:
clear_cache()
seed = json.loads(catalog_data._PACKAGE_SEED_PATH.read_text(encoding="utf-8"))
plugin = next(item for item in seed["plugins"] if item["id"] == "slack")
+ plugin.pop("native_tool", None)
+ plugin["mcp_server"] = json.loads(json.dumps(_HOSTED_SLACK_MCP))
plugin["auth"] = {
"mode": "oauth_pkce_loopback",
"authorization_url": "https://slack.com/oauth/v2/authorize",
@@ -125,19 +159,7 @@ def test_slack_scope_upgrade_preserves_custom_auth_and_disk(monkeypatch, tmp_pat
"revocation_url": "https://slack.com/api/auth.revoke",
"client_id": "REPLACE_WITH_JARVIS_SLACK_APP_CLIENT_ID",
"callback_port": 3118,
- "scopes": [
- "chat:write",
- "users:read",
- "users:read.email",
- "search:read.public",
- "search:read.private",
- "search:read.im",
- "search:read.mpim",
- "channels:history",
- "groups:history",
- "im:history",
- "mpim:history",
- ],
+ "scopes": list(legacy),
"user_scopes_only": True,
"refresh_supported": True,
"refresh_token_ttl_days": 30,
@@ -158,6 +180,7 @@ def test_slack_scope_upgrade_preserves_custom_auth_and_disk(monkeypatch, tmp_pat
slack = load_catalog().by_id("slack")
assert slack is not None
+ assert slack.native_tool == "slack"
if custom:
from jarvis.marketplace.catalog import PluginCatalog
@@ -165,8 +188,8 @@ def test_slack_scope_upgrade_preserves_custom_auth_and_disk(monkeypatch, tmp_pat
assert slack.auth == expected.auth
assert slack.mcp_server == expected.mcp_server
else:
- assert "canvases:write" in slack.auth.scopes
- assert "channels:read" in slack.auth.scopes
+ assert slack.auth == _seed().by_id("slack").auth
+ assert slack.mcp_server is None
assert override.read_text(encoding="utf-8") == content
clear_cache()
diff --git a/tests/unit/marketplace/test_connection_verification.py b/tests/unit/marketplace/test_connection_verification.py
index 4e852e713e..3bc44d43b4 100644
--- a/tests/unit/marketplace/test_connection_verification.py
+++ b/tests/unit/marketplace/test_connection_verification.py
@@ -101,6 +101,41 @@ async def test_native_uses_authenticated_resource_read(monkeypatch, status, payl
assert requests[0].headers["Authorization"] == "Bearer t"
+ "payload,accepted",
+ [
+ ({"ok": True, "user_id": "U1", "team_id": "T1"}, True),
+ ({"ok": False, "error": "invalid_auth"}, False),
+ ({"ok": False, "user_id": "U1"}, False),
+ ],
+)
+async def test_slack_verifies_with_side_effect_free_auth_test(monkeypatch, payload, accepted):
+ """Slack reports failures as HTTP 200 + ok=false; auth.test writes nothing."""
+ original = httpx.AsyncClient
+ requests = []
+
+ def handle(request):
+ requests.append(request)
+ return httpx.Response(200, json=payload)
+
+ monkeypatch.setattr(
+ verification.httpx,
+ "AsyncClient",
+ lambda **kwargs: original(**kwargs, transport=httpx.MockTransport(handle)),
+ )
+ if accepted:
+ await verification.verify_connection(plugin("slack"), Tokens(access="t"))
+ else:
+ with pytest.raises(verification.ConnectionVerificationError) as caught:
+ await verification.verify_connection(plugin("slack"), Tokens(access="t"))
+ assert "invalid_auth" not in str(caught.value)
+ assert len(requests) == 1
+ assert requests[0].method == "GET"
+ assert str(requests[0].url) == "https://slack.com/api/auth.test"
+ assert requests[0].headers["Authorization"] == "Bearer t"
+
+
@pytest.mark.asyncio
async def test_unknown_verifier_fails_closed():
spec = plugin("gmail").model_copy(update={"id": "unknown", "native_tool": "unknown"})
diff --git a/tests/unit/plugins/tool/test_slack_rest.py b/tests/unit/plugins/tool/test_slack_rest.py
new file mode 100644
index 0000000000..3124c059d0
--- /dev/null
+++ b/tests/unit/plugins/tool/test_slack_rest.py
@@ -0,0 +1,476 @@
+"""Slack REST tool: calls the Slack Web API with the marketplace user token.
+
+Native instead of Slack's hosted MCP server, which admits only
+Marketplace-listed or internal apps. All HTTP goes through httpx.MockTransport.
+"""
+
+from __future__ import annotations
+
+import json
+
+import httpx
+import pytest
+
+from jarvis.plugins.tool.slack_rest import SlackRestTool
+
+_C = "C0123ABCD"
+
+
+def _ok(**body):
+ return httpx.Response(200, json={"ok": True, **body})
+
+
+def _fail(code: str, **extra):
+ return httpx.Response(200, json={"ok": False, "error": code, **extra})
+
+
+def _tool(handler, *, access: str | None = "xoxp-at", refresher=None, sleeps=None):
+ tokens = {"value": access}
+
+ async def _sleep(seconds: float) -> None:
+ if sleeps is not None:
+ sleeps.append(seconds)
+
+ tool = SlackRestTool(
+ access_token_provider=lambda: tokens["value"],
+ transport=httpx.MockTransport(handler),
+ token_refresher=refresher,
+ sleep=_sleep,
+ )
+ return tool, tokens
+
+
+def _method(req: httpx.Request) -> str:
+ return req.url.path.rsplit("/", 1)[-1]
+
+
+async def test_search_messages_uses_bearer_and_slims_matches():
+ seen = []
+
+ def handler(req):
+ seen.append(req)
+ assert _method(req) == "search.messages"
+ return _ok(
+ messages={
+ "total": 1,
+ "paging": {"page": 1, "pages": 1},
+ "matches": [
+ {
+ "channel": {"id": _C, "name": "general"},
+ "user": "U0AAAAAAA",
+ "username": "anna",
+ "text": "Release is on Friday",
+ "ts": "1700000000.000100",
+ "permalink": "https://example.slack.com/archives/C0123ABCD/p1",
+ "blocks": [{"huge": "payload"}],
+ }
+ ],
+ }
+ )
+
+ tool, _ = _tool(handler)
+ result = await tool.execute({"action": "search_messages", "query": "release"}, None)
+ assert result.success, result.error
+ assert seen[0].headers["authorization"] == "Bearer xoxp-at"
+ assert seen[0].url.params["query"] == "release"
+ assert seen[0].url.params["sort"] == "timestamp"
+ message = result.output["messages"][0]
+ assert message == {
+ "channel_id": _C,
+ "channel": "general",
+ "user": "U0AAAAAAA",
+ "user_name": "anna",
+ "text": "Release is on Friday",
+ "ts": "1700000000.000100",
+ "permalink": "https://example.slack.com/archives/C0123ABCD/p1",
+ }
+ assert result.output["total"] == 1
+
+
+async def test_list_conversations_follows_cursor_and_names_dms():
+ pages = []
+
+ def handler(req):
+ method = _method(req)
+ if method == "conversations.list":
+ pages.append(dict(req.url.params))
+ if "cursor" not in req.url.params:
+ return _ok(
+ channels=[{"id": _C, "name": "general", "is_channel": True, "is_member": True}],
+ response_metadata={"next_cursor": "page2"},
+ )
+ return _ok(
+ channels=[{"id": "D0123ABCD", "is_im": True, "user": "U0BBBBBBB"}],
+ response_metadata={"next_cursor": ""},
+ )
+ if method == "users.info":
+ assert req.url.params["user"] == "U0BBBBBBB"
+ return _ok(user={"id": "U0BBBBBBB", "profile": {"display_name": "Ben"}})
+ raise AssertionError(method)
+
+ tool, _ = _tool(handler)
+ out = await tool.list_conversations()
+ assert pages[0]["types"] == "public_channel,private_channel,mpim,im"
+ assert pages[0]["exclude_archived"] == "true"
+ assert pages[1]["cursor"] == "page2"
+ assert out["count"] == 2
+ assert out["conversations"][0]["kind"] == "channel"
+ assert out["conversations"][1] == {
+ "id": "D0123ABCD",
+ "name": "Ben",
+ "kind": "dm",
+ "user": "U0BBBBBBB",
+ }
+ assert "next_cursor" not in out
+
+
+async def test_list_conversations_returns_cursor_when_limit_reached():
+ def handler(req):
+ return _ok(
+ channels=[{"id": _C, "name": "general"}],
+ response_metadata={"next_cursor": "more"},
+ )
+
+ tool, _ = _tool(handler)
+ out = await tool.list_conversations(limit=1, types="public_channel")
+ assert out["count"] == 1
+ assert out["next_cursor"] == "more"
+
+
+async def test_read_history_resolves_channel_name_and_user_names():
+ calls = []
+
+ def handler(req):
+ method = _method(req)
+ calls.append(method)
+ if method == "conversations.list":
+ assert req.url.params["types"] == "public_channel,private_channel,mpim"
+ return _ok(channels=[{"id": "C0OTHER00", "name": "random"}, {"id": _C, "name": "team"}])
+ if method == "conversations.history":
+ assert req.url.params["channel"] == _C
+ return _ok(
+ messages=[
+ {
+ "ts": "2",
+ "user": "U0AAAAAAA",
+ "text": "hi",
+ "reply_count": 3,
+ "thread_ts": "2",
+ }
+ ],
+ has_more=True,
+ response_metadata={"next_cursor": "older"},
+ )
+ if method == "users.info":
+ return _ok(user={"id": "U0AAAAAAA", "real_name": "Anna Example"})
+ raise AssertionError(method)
+
+ tool, _ = _tool(handler)
+ result = await tool.execute({"action": "read_history", "channel": "#team"}, None)
+ assert result.success, result.error
+ out = result.output
+ assert out["channel_id"] == _C
+ assert out["messages"][0]["user_name"] == "Anna Example"
+ assert out["messages"][0]["reply_count"] == 3
+ assert out["next_cursor"] == "older"
+ assert calls == ["conversations.list", "conversations.history", "users.info"]
+
+
+async def test_read_thread_passes_ts():
+ def handler(req):
+ assert _method(req) == "conversations.replies"
+ assert req.url.params["ts"] == "1700.1"
+ return _ok(messages=[{"ts": "1700.1", "bot_id": "B1", "text": "parent"}], has_more=False)
+
+ tool, _ = _tool(handler)
+ out = await tool.read_thread(channel=_C, thread_ts="1700.1")
+ assert out["messages"][0]["text"] == "parent"
+ assert out["order"] == "oldest first"
+
+
+async def test_dm_resolution_uses_existing_im_only():
+ def handler(req):
+ method = _method(req)
+ if method == "users.list":
+ return _ok(
+ members=[
+ {"id": "U0AAAAAAA", "name": "anna", "real_name": "Anna Example"},
+ {"id": "U0CCCCCCC", "name": "carl", "real_name": "Carl"},
+ ]
+ )
+ if method == "conversations.list":
+ assert req.url.params["types"] == "im"
+ return _ok(channels=[{"id": "D0123ABCD", "is_im": True, "user": "U0AAAAAAA"}])
+ if method == "conversations.history":
+ assert req.url.params["channel"] == "D0123ABCD"
+ return _ok(messages=[], has_more=False)
+ if method == "users.info":
+ raise AssertionError("directory already named the user")
+ raise AssertionError(method)
+
+ tool, _ = _tool(handler)
+ out = await tool.read_history(channel="@anna")
+ assert out["channel_id"] == "D0123ABCD"
+
+
+async def test_dm_without_existing_conversation_is_reported_not_opened():
+ def handler(req):
+ method = _method(req)
+ if method == "users.list":
+ return _ok(members=[{"id": "U0AAAAAAA", "name": "anna"}])
+ if method == "conversations.list":
+ return _ok(channels=[])
+ raise AssertionError(f"must not call {method}")
+
+ tool, _ = _tool(handler)
+ result = await tool.execute(
+ {"action": "post_message", "channel": "@anna", "text": "hi"}, None
+ )
+ assert not result.success
+ assert "no direct message" in result.error
+
+
+async def test_ambiguous_person_returns_candidates():
+ def handler(req):
+ return _ok(
+ members=[
+ {"id": "U0AAAAAAA", "name": "anna.a", "real_name": "Anna A"},
+ {"id": "U0BBBBBBB", "name": "anna.b", "real_name": "Anna B"},
+ ]
+ )
+
+ tool, _ = _tool(handler)
+ result = await tool.execute({"action": "read_history", "channel": "@anna"}, None)
+ assert not result.success
+ assert "Several people" in result.error
+ assert {c["id"] for c in result.output["candidates"]} == {"U0AAAAAAA", "U0BBBBBBB"}
+
+
+async def test_unknown_channel_name_is_never_guessed():
+ def handler(req):
+ return _ok(channels=[{"id": _C, "name": "general"}])
+
+ tool, _ = _tool(handler)
+ result = await tool.execute({"action": "read_history", "channel": "#nope"}, None)
+ assert not result.success
+ assert "#nope" in result.error
+
+
+async def test_post_message_sends_json_with_thread():
+ seen = []
+
+ def handler(req):
+ seen.append(req)
+ assert _method(req) == "chat.postMessage"
+ return _ok(channel=_C, ts="1700.2")
+
+ tool, _ = _tool(handler)
+ result = await tool.execute(
+ {"action": "post_message", "channel": _C, "text": "On my way", "thread_ts": "1700.1"},
+ None,
+ )
+ assert result.success, result.error
+ assert seen[0].method == "POST"
+ assert seen[0].headers["content-type"].startswith("application/json")
+ assert json.loads(seen[0].content) == {
+ "channel": _C,
+ "text": "On my way",
+ "thread_ts": "1700.1",
+ }
+ assert result.output == {
+ "posted": True,
+ "channel_id": _C,
+ "ts": "1700.2",
+ "thread_ts": "1700.1",
+ }
+
+
+async def test_post_message_rejects_empty_text_without_calling_slack():
+ def handler(req):
+ raise AssertionError("no call expected")
+
+ tool, _ = _tool(handler)
+ result = await tool.execute({"action": "post_message", "channel": _C, "text": " "}, None)
+ assert not result.success
+ assert "empty" in result.error
+
+
+async def test_token_expired_refreshes_once_and_retries():
+ attempts = []
+ refreshes = []
+
+ def handler(req):
+ attempts.append(req.headers["authorization"])
+ if req.headers["authorization"] == "Bearer xoxp-old":
+ return _fail("token_expired")
+ return _ok(user={"id": "U0AAAAAAA", "name": "anna"})
+
+ async def refresher():
+ refreshes.append(1)
+ tokens["value"] = "xoxp-new"
+ return True
+
+ tool, tokens = _tool(handler, access="xoxp-old", refresher=refresher)
+ out = await tool.get_user(user="U0AAAAAAA")
+ assert out["name"] == "anna"
+ assert attempts == ["Bearer xoxp-old", "Bearer xoxp-new"]
+ assert refreshes == [1]
+
+
+async def test_failed_refresh_asks_for_reconnect():
+ def handler(req):
+ return _fail("token_expired")
+
+ async def refresher():
+ return False
+
+ tool, _ = _tool(handler, refresher=refresher)
+ result = await tool.execute({"action": "get_user", "user": "U0AAAAAAA"}, None)
+ assert not result.success
+ assert "reconnect Slack" in result.error
+
+
+async def test_revoked_token_does_not_try_refresh():
+ async def refresher():
+ raise AssertionError("revoked tokens cannot be refreshed")
+
+ tool, _ = _tool(lambda req: _fail("token_revoked"), refresher=refresher)
+ result = await tool.execute({"action": "search_messages", "query": "x"}, None)
+ assert not result.success
+ assert "reconnect Slack" in result.error
+
+
+async def test_provider_error_text_never_reaches_the_result():
+ leaked = "xoxp-LEAKED-value"
+
+ def handler(req):
+ return _fail(leaked, detail=leaked)
+
+ tool, _ = _tool(handler)
+ result = await tool.execute({"action": "search_messages", "query": "x"}, None)
+ assert not result.success
+ assert leaked not in result.error
+ assert result.error == "Slack could not complete the request. Try again in a moment."
+
+
+async def test_missing_scope_explains_reconnect():
+ tool, _ = _tool(lambda req: _fail("missing_scope", needed="search:read"))
+ result = await tool.execute({"action": "search_messages", "query": "x"}, None)
+ assert not result.success
+ assert "permission" in result.error
+
+
+async def test_short_rate_limit_is_absorbed_once():
+ sleeps = []
+ calls = []
+
+ def handler(req):
+ calls.append(1)
+ if len(calls) == 1:
+ return httpx.Response(429, headers={"Retry-After": "1"})
+ return _ok(messages={"matches": [], "total": 0})
+
+ tool, _ = _tool(handler, sleeps=sleeps)
+ out = await tool.search_messages(query="x")
+ assert out["messages"] == []
+ assert sleeps == [1.0]
+ assert len(calls) == 2
+
+
+async def test_long_rate_limit_is_reported_with_wait():
+ sleeps = []
+ tool, _ = _tool(
+ lambda req: httpx.Response(429, headers={"Retry-After": "30"}), sleeps=sleeps
+ )
+ result = await tool.execute({"action": "post_message", "channel": _C, "text": "hi"}, None)
+ assert not result.success
+ assert "30 seconds" in result.error
+ assert sleeps == []
+
+
+async def test_not_connected():
+ tool, _ = _tool(lambda req: _ok(), access=None)
+ result = await tool.execute({"action": "list_conversations"}, None)
+ assert not result.success
+ assert "not connected" in result.error
+
+
+async def test_server_error_is_explained_without_body():
+ tool, _ = _tool(lambda req: httpx.Response(503, text="internal xoxp-secret"))
+ result = await tool.execute({"action": "find_users", "query": "anna"}, None)
+ assert not result.success
+ assert "xoxp" not in result.error
+ assert "trouble" in result.error
+
+
+def test_risk_tiers_reads_safe_post_asks():
+ tool = SlackRestTool(access_token_provider=lambda: "t")
+ for action in (
+ "search_messages",
+ "list_conversations",
+ "read_history",
+ "read_thread",
+ "get_user",
+ "find_users",
+ ):
+ assert tool.risk_tier_for_args({"action": action}) == "safe"
+ assert tool.risk_tier_for_args({"action": "post_message"}) == "ask"
+ assert tool.risk_tier_for_args({"action": "something_else"}) == "ask"
+ assert tool.risk_tier == "ask"
+
+
+def test_entry_point_and_catalog_bind_the_tool():
+ import tomllib
+ from pathlib import Path
+
+ from jarvis.marketplace.catalog import PluginCatalog
+ from jarvis.marketplace.catalog_data import _PACKAGE_SEED_PATH
+
+ root = Path(__file__).resolve().parents[4]
+ pyproject = tomllib.loads((root / "pyproject.toml").read_text(encoding="utf-8"))
+ tools = pyproject["project"]["entry-points"]["jarvis.tool"]
+ assert tools["slack"] == "jarvis.plugins.tool.slack_rest:SlackRestTool"
+
+ catalog = PluginCatalog.model_validate(
+ json.loads(_PACKAGE_SEED_PATH.read_text(encoding="utf-8"))
+ )
+ slack = catalog.by_id("slack")
+ assert slack is not None
+ assert slack.native_tool == "slack"
+ assert slack.mcp_server is None
+ assert slack.auth.mode == "oauth_pkce_loopback"
+ assert slack.auth.callback_port == 3118
+ assert slack.auth.user_scopes_only is True
+ assert slack.auth.scopes == [
+ "chat:write",
+ "users:read",
+ "search:read",
+ "channels:history",
+ "groups:history",
+ "im:history",
+ "mpim:history",
+ "channels:read",
+ "groups:read",
+ "im:read",
+ "mpim:read",
+ ]