Repository navigation
feat(agent): add opt-in read-only MCP bridge #286
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
77d79b3
feat(agent): add opt-in read-only MCP bridge
DavidHLP d28b6c0
fix(agent): refresh repository corpus digest
DavidHLP 7e44463
fix(agent): retain base documentation digest
DavidHLP 8d27a31
Merge remote-tracking branch 'origin/main' into HEAD
DavidHLP File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,119 @@ | ||
| """Request-scoped MCP Client bridge for the one allowlisted submission tool.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import asyncio | ||
| from contextlib import AsyncExitStack | ||
|
|
||
| from mcp import Client | ||
|
|
||
| from agent_mcp_server import TOOL_NAME, create_server | ||
| from ulticode_tools import parse_my_submissions_arguments, project_my_submissions_listing | ||
|
|
||
| MCP_CALL_TIMEOUT_SECONDS = 5.0 | ||
| _TOOL_ERRORS = {"business_error", "invalid_arguments", "tool_error"} | ||
|
|
||
|
|
||
| class MCPProtocolError(RuntimeError): | ||
| """The expected read-only MCP tool could not be discovered safely.""" | ||
|
|
||
|
|
||
| def _valid_tool_definition(tool: object) -> bool: | ||
| schema = getattr(tool, "input_schema", None) | ||
| if not isinstance(schema, dict): | ||
| return False | ||
| properties = schema.get("properties") | ||
| if not isinstance(properties, dict) or set(properties) != {"page", "pageSize"}: | ||
| return False | ||
| if schema.get("required", []) != []: | ||
| return False | ||
| return all( | ||
| isinstance(properties[name], dict) | ||
| and properties[name].get("type") == "integer" | ||
| for name in ("page", "pageSize") | ||
| ) | ||
|
|
||
|
|
||
| class MCPSubmissionSession: | ||
| """Discover once before the model loop and close the protocol session after it.""" | ||
|
|
||
| def __init__(self, business_client: object) -> None: | ||
| self._business_client = business_client | ||
| self._stack: AsyncExitStack | None = None | ||
| self.client: Client | None = None | ||
|
|
||
| async def __aenter__(self) -> dict[str, object]: | ||
| stack = AsyncExitStack() | ||
| self._stack = stack | ||
| try: | ||
| self.client = await stack.enter_async_context( | ||
| Client( | ||
| create_server(self._business_client), | ||
| read_timeout_seconds=MCP_CALL_TIMEOUT_SECONDS, | ||
| ) | ||
| ) | ||
| discovered = await self.client.list_tools(cache_mode="refresh") | ||
| if ( | ||
| discovered.next_cursor is not None | ||
| or len(discovered.tools) != 1 | ||
| or discovered.tools[0].name != TOOL_NAME | ||
| or not _valid_tool_definition(discovered.tools[0]) | ||
| ): | ||
| raise MCPProtocolError("mcp_discovery_failed") | ||
| except asyncio.CancelledError: | ||
| await stack.aclose() | ||
| self._stack = None | ||
| self.client = None | ||
| raise | ||
| except Exception: | ||
| await stack.aclose() | ||
| self._stack = None | ||
| self.client = None | ||
| raise MCPProtocolError("mcp_discovery_failed") from None | ||
| return {TOOL_NAME: self._call} | ||
|
|
||
| async def __aexit__(self, exc_type, exc_value, traceback) -> None: | ||
| stack, self._stack = self._stack, None | ||
| self.client = None | ||
| if stack is not None: | ||
| await stack.__aexit__(exc_type, exc_value, traceback) | ||
|
|
||
| async def _call(self, arguments: dict[str, object]) -> object: | ||
| try: | ||
| page, page_size = parse_my_submissions_arguments(arguments) | ||
| except (TypeError, ValueError): | ||
| return {"error": "invalid_arguments"} | ||
| if self.client is None: | ||
| return {"error": "protocol_error"} | ||
| try: | ||
| async with asyncio.timeout(MCP_CALL_TIMEOUT_SECONDS): | ||
| result = await self.client.call_tool( | ||
| TOOL_NAME, | ||
| {"page": page, "pageSize": page_size}, | ||
| read_timeout_seconds=MCP_CALL_TIMEOUT_SECONDS, | ||
| ) | ||
| except TimeoutError: | ||
| return {"error": "timeout"} | ||
| except asyncio.CancelledError: | ||
| raise | ||
| except Exception: | ||
| return {"error": "protocol_error"} | ||
|
|
||
| if result.is_error: | ||
| safe_text = " ".join( | ||
| text for item in result.content | ||
| if isinstance((text := getattr(item, "text", None)), str) | ||
| ) | ||
| label = next( | ||
| (error for error in _TOOL_ERRORS if error in safe_text), | ||
| "business_error", | ||
| ) | ||
| return {"error": label} | ||
| try: | ||
| return project_my_submissions_listing( | ||
| result.structured_content, | ||
| page=page, | ||
| page_size=page_size, | ||
| ) | ||
| except (TypeError, ValueError): | ||
| return {"error": "protocol_error"} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,80 @@ | ||
| """One local MCP endpoint over the existing authenticated read-only tool.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import asyncio | ||
| import os | ||
| import sys | ||
|
|
||
| from mcp.server import MCPServer | ||
| from mcp.server.mcpserver.exceptions import ToolError | ||
| from pydantic import StrictInt | ||
|
|
||
| from ulticode_client import UlticodeClient, UlticodeError | ||
| from ulticode_tools import build_tools, parse_my_submissions_arguments | ||
|
|
||
| TOOL_NAME = "get_my_submissions" | ||
| TOOL_DESCRIPTION = ( | ||
| "Read the authenticated user's paged submission metadata. Java enforces the " | ||
| "session and owner scope; source code and user identity fields are excluded." | ||
| ) | ||
|
|
||
|
|
||
| def create_server(client: UlticodeClient) -> MCPServer: | ||
| handler = build_tools(client)[TOOL_NAME] | ||
| server = MCPServer(name="ulticode-agent-readonly", version="0.1.0") | ||
|
|
||
| @server.tool( | ||
| name=TOOL_NAME, | ||
| description=TOOL_DESCRIPTION, | ||
| structured_output=True, | ||
| ) | ||
| async def get_my_submissions( | ||
| page: StrictInt = 1, pageSize: StrictInt = 5 | ||
| ) -> dict[str, object]: | ||
| try: | ||
| normalized_page, page_size = parse_my_submissions_arguments( | ||
| {"page": page, "pageSize": pageSize} | ||
| ) | ||
| except ValueError: | ||
| raise ToolError("invalid_arguments") from None | ||
| try: | ||
| return await handler({"page": normalized_page, "pageSize": page_size}) # type: ignore[no-any-return] | ||
| except UlticodeError: | ||
| raise ToolError("business_error") from None | ||
| except ValueError: | ||
| raise ToolError("business_error") from None | ||
| except Exception: | ||
| raise ToolError("tool_error") from None | ||
|
|
||
| return server | ||
|
|
||
|
|
||
| async def _run_stdio() -> None: | ||
| app_base = os.environ.get("ULTICODE_APP_BASE", "") | ||
| auth_base = os.environ.get("ULTICODE_AUTH_BASE", "") | ||
| access_token = os.environ.get("ULTICODE_AGENT_ACCESS_TOKEN", "") | ||
| csrf_token = os.environ.get("ULTICODE_AGENT_CSRF_TOKEN") or None | ||
| if not app_base or not auth_base or not access_token: | ||
| raise ValueError("mcp_configuration_invalid") | ||
|
|
||
| client = UlticodeClient.for_session( | ||
| app_base, | ||
| auth_base, | ||
| access_token=access_token, | ||
| csrf_token=csrf_token, | ||
| ) | ||
| async with client: | ||
| await create_server(client).run_stdio_async() | ||
|
|
||
|
|
||
| def main() -> None: | ||
| try: | ||
| asyncio.run(_run_stdio()) | ||
| except (ValueError, RuntimeError): | ||
| print("mcp_configuration_or_runtime_error", file=sys.stderr) | ||
| raise SystemExit(2) from None | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| main() | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
In the documented standalone stdio configuration, this reads the user's bearer access token from an environment variable, requiring it to be copied out of its HttpOnly cookie and exposing it to process-environment readers and inherited child processes. That bypasses the repository's explicit token-storage boundary; authenticate the standalone bridge through a host-mediated cookie/session channel rather than provisioning the raw token in
ULTICODE_AGENT_ACCESS_TOKEN.AGENTS.md reference: AGENTS.md:L55-L56
Useful? React with 👍 / 👎.