fix(linear): retain issue context and clarify OAuth diagnostics

This commit is contained in:
chengyongru authored and chengyongru committed 2026-09-23 18:29:52 +08:00
1 parent 1fc44e091b
commit f9048dc514
5 files changed
+193 -13

No files matched your search

+22
View File
@@ -10,6 +10,7 @@ from __future__ import annotations
import asyncio
import hashlib
import json
import logging
import math
import os
import secrets
@@ -70,6 +71,24 @@ class MCPAuthorizationRequiredError(RuntimeError):
"""Raised when a background MCP connection needs interactive authorization."""
class _OAuthAuthorizationLogFilter(logging.Filter):
"""Keep the SDK's expected authorization interruption out of error tracebacks."""
def filter(self, record: logging.LogRecord) -> bool:
if (
record.getMessage() == "OAuth flow error"
and record.exc_info
and isinstance(record.exc_info[1], MCPAuthorizationRequiredError)
):
record.levelno = logging.INFO
record.levelname = "INFO"
record.msg = "MCP OAuth request paused at browser authorization"
record.args = ()
record.exc_info = None
record.exc_text = None
return True
@dataclass(frozen=True)
class MCPOAuthHandlers:
"""Browser callbacks supplied only for a user-initiated OAuth attempt."""
@@ -815,6 +834,9 @@ async def create_mcp_oauth_auth(
handlers: MCPOAuthHandlers | None = None,
) -> OAuthClientProvider:
"""Build the official MCP SDK OAuth provider for one configured server."""
sdk_logger = logging.getLogger("mcp.client.auth.oauth2")
if not any(isinstance(f, _OAuthAuthorizationLogFilter) for f in sdk_logger.filters):
sdk_logger.addFilter(_OAuthAuthorizationLogFilter())
storage = MCPOAuthStorage(server_name, server_url)
if handlers is not None:
await storage.prepare_redirect_uri(
+25 -2
View File
@@ -375,7 +375,9 @@ class LinearChannel(BaseChannel):
"linear": {
"organization_id": organization_id,
"agent_session_id": agent_session_id,
"issue_id": str(session.get("issueId") or ""),
"issue_id": str(
session.get("issueId") or _optional_object(session.get("issue")).get("id") or ""
),
"comment_id": str(session.get("commentId") or ""),
"app_user_id": installation.app_user_id,
"oauth_client_id": str(payload.get("oauthClientId") or ""),
@@ -515,9 +517,30 @@ def _prompt_text(
value: object
if action == "created":
value = payload.get("promptContext")
if context := _text_from_value(value):
return context
text = _text_from_value(session.get("comment"))
else:
value = activity.get("body") or activity.get("content")
return _text_from_value(value) or _text_from_value(session.get("comment"))
text = _text_from_value(value) or _text_from_value(session.get("comment"))
if not text or text.startswith("/"):
return text
context = _issue_context(session)
return "\n\n".join(part for part in (context, text) if part)
def _issue_context(session: dict[str, Any]) -> str:
"""Include issue identity even when pairing prevented the initial turn."""
issue = _optional_object(session.get("issue"))
fields: dict[str, str] = {}
for key, limit in (("id", 200), ("identifier", 200), ("title", 500),
("url", 2048), ("description", 12000)):
value = issue.get(key) or (session.get("issueId") if key == "id" else None)
if isinstance(value, str) and value.strip():
fields[key] = value.strip()[:limit]
if not fields:
return ""
return "Current Linear issue:\n" + json.dumps(fields, ensure_ascii=False)
def _text_from_value(value: object) -> str:
@@ -723,6 +723,57 @@ async def test_created_agent_session_publishes_only_the_mention_prompt(tmp_path:
assert client.activities[0]["content"] == {"type": "thought", "body": "Starting…"}
@pytest.mark.asyncio
async def test_followup_after_pairing_includes_current_issue(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
) -> None:
channel, _ = _runtime(tmp_path)
monkeypatch.setattr(channel, "is_allowed", lambda _sender: False)
await channel._process_webhook("unpaired", _agent_webhook()) # pyright: ignore[reportPrivateUsage]
assert channel.bus.inbound.empty()
monkeypatch.setattr(channel, "is_allowed", lambda _sender: True)
payload = _agent_webhook(action="prompted")
payload.pop("promptContext")
payload["agentSession"].pop("issueId")
payload["agentSession"]["issue"] = {
"id": "issue-1", "identifier": "CHE-6", "title": "Update documentation",
"description": "Document webhook delivery setup.",
"url": "https://linear.app/example/issue/CHE-6",
}
payload["agentActivity"]["body"] = "What is the current task?"
await channel._process_webhook("paired-followup", payload) # pyright: ignore[reportPrivateUsage]
inbound = await channel.bus.consume_inbound()
assert "CHE-6" in inbound.content
assert "Update documentation" in inbound.content
assert "Document webhook delivery setup." in inbound.content
assert inbound.content.endswith("What is the current task?")
assert inbound.metadata["linear"]["issue_id"] == "issue-1"
@pytest.mark.asyncio
@pytest.mark.parametrize("action", ["created", "prompted"])
async def test_issue_id_remains_visible_without_structured_details(
tmp_path: Path, action: str,
) -> None:
channel, _ = _runtime(tmp_path)
payload = _agent_webhook(action=action)
payload.pop("promptContext")
await channel._process_webhook("issue-id-only", payload) # pyright: ignore[reportPrivateUsage]
inbound = await channel.bus.consume_inbound()
assert '"id": "issue-1"' in inbound.content
@pytest.mark.asyncio
async def test_followup_slash_command_is_not_wrapped_in_issue_context(tmp_path: Path) -> None:
channel, _ = _runtime(tmp_path)
payload = _agent_webhook(action="prompted")
payload["agentActivity"]["body"] = "/help"
await channel._process_webhook("command", payload) # pyright: ignore[reportPrivateUsage]
assert (await channel.bus.consume_inbound()).content == "/help"
@pytest.mark.asyncio
async def test_created_session_downloads_private_linear_attachments(
tmp_path: Path,