feat(mcp): scaffold three project context tools
CI / test (pull_request) Canceled after 0s

This commit is contained in:
thanhnv
2026-08-20 20:50:37 +07:00
parent 3827552909
commit 202925e6ed
17 changed files with 921 additions and 0 deletions
+5
View File
@@ -0,0 +1,5 @@
"""Provider-neutral Project Context MCP server template."""
from .server import build_server, dispatch
__all__ = ["build_server", "dispatch"]
+106
View File
@@ -0,0 +1,106 @@
"""Shared, stable boundary used by all Project Context tool work packages."""
from __future__ import annotations
from collections.abc import Callable
from dataclasses import dataclass
from datetime import datetime
from typing import Any, Protocol
from pydantic import AnyUrl, BaseModel, ConfigDict, Field
class ContractModel(BaseModel):
"""Strict immutable model so provider-specific fields cannot leak to the Agent."""
model_config = ConfigDict(extra="forbid", frozen=True)
class IdentityContext(ContractModel):
actor_id: str = Field(min_length=1, max_length=256)
org_unit: str = Field(min_length=1, max_length=128)
customer: str = Field(min_length=1, max_length=128)
project: str = Field(min_length=1, max_length=128)
granted_scopes: frozenset[str]
class SourceCitation(ContractModel):
system: str = Field(min_length=1, max_length=64)
url: AnyUrl
revision: str = Field(min_length=1, max_length=256)
retrieved_at: datetime
@dataclass(frozen=True)
class DispatchResult:
ok: bool
payload: dict[str, Any]
class PolicyDecisionPoint(Protocol):
def decide(self, identity: IdentityContext, tool_name: str, project_id: str) -> bool: ...
class CredentialResolver(Protocol):
def resolve(self, identity: IdentityContext, tool_name: str) -> Any: ...
@dataclass(frozen=True)
class ProjectContextRuntime:
identity: IdentityContext
policy: PolicyDecisionPoint
credential_resolver: CredentialResolver
class ProviderError(RuntimeError):
"""A provider failure with a caller-safe message and retry classification."""
def __init__(self, code: str, message: str, *, retryable: bool) -> None:
super().__init__(message)
self.code = code
self.safe_message = message
self.retryable = retryable
ToolHandler = Callable[[ContractModel, Any], dict[str, Any]]
@dataclass(frozen=True)
class ToolTemplate:
name: str
description: str
input_model: type[ContractModel]
output_model: type[ContractModel]
handler: ToolHandler
def declaration(self) -> dict[str, Any]:
return {
"name": self.name,
"description": self.description,
"inputSchema": self.input_model.model_json_schema(),
"outputSchema": self.output_model.model_json_schema(),
}
def error_result(
code: str,
*,
category: str,
retryable: bool,
message: str,
suggested_action: str,
correlation_id: str,
) -> DispatchResult:
return DispatchResult(
ok=False,
payload={
"error": {
"code": code,
"category": category,
"retryable": retryable,
"message": message,
"suggested_action": suggested_action,
"correlation_id": correlation_id,
}
},
)
@@ -0,0 +1 @@
"""One provider module per member-owned tool work package."""
@@ -0,0 +1,25 @@
"""Provider boundary owned with get_project_change_context."""
from __future__ import annotations
from typing import Any, Protocol
from ..foundation import IdentityContext, ProviderError
class ChangeProvider(Protocol):
def get_change_context(self, **arguments: Any) -> dict[str, Any]: ...
class UnconfiguredChangeProvider:
def get_change_context(self, **arguments: Any) -> dict[str, Any]:
raise ProviderError(
"UNAVAILABLE",
"The change provider is not configured for this environment.",
retryable=False,
)
def build_provider(identity: IdentityContext) -> ChangeProvider:
"""Replace only this factory when wiring the approved read-only Git adapter."""
return UnconfiguredChangeProvider()
@@ -0,0 +1,25 @@
"""Provider boundary owned with get_project_issue_context."""
from __future__ import annotations
from typing import Any, Protocol
from ..foundation import IdentityContext, ProviderError
class IssueProvider(Protocol):
def get_issue_context(self, **arguments: Any) -> dict[str, Any]: ...
class UnconfiguredIssueProvider:
def get_issue_context(self, **arguments: Any) -> dict[str, Any]:
raise ProviderError(
"UNAVAILABLE",
"The issue provider is not configured for this environment.",
retryable=False,
)
def build_provider(identity: IdentityContext) -> IssueProvider:
"""Replace only this factory when wiring the approved read-only issue adapter."""
return UnconfiguredIssueProvider()
@@ -0,0 +1,25 @@
"""Provider boundary owned with search_project_knowledge."""
from __future__ import annotations
from typing import Any, Protocol
from ..foundation import IdentityContext, ProviderError
class KnowledgeProvider(Protocol):
def search_knowledge(self, **arguments: Any) -> dict[str, Any]: ...
class UnconfiguredKnowledgeProvider:
def search_knowledge(self, **arguments: Any) -> dict[str, Any]:
raise ProviderError(
"UNAVAILABLE",
"The knowledge provider is not configured for this environment.",
retryable=False,
)
def build_provider(identity: IdentityContext) -> KnowledgeProvider:
"""Replace only this factory when wiring approved project retrieval."""
return UnconfiguredKnowledgeProvider()
+23
View File
@@ -0,0 +1,23 @@
"""Immutable registry composed before member work starts to prevent merge conflicts."""
from __future__ import annotations
from types import MappingProxyType
from typing import Any
from .foundation import ToolTemplate
from .tools.change_context import TOOL as CHANGE_CONTEXT_TOOL
from .tools.issue_context import TOOL as ISSUE_CONTEXT_TOOL
from .tools.knowledge_search import TOOL as KNOWLEDGE_SEARCH_TOOL
TOOLS: tuple[ToolTemplate, ...] = (
ISSUE_CONTEXT_TOOL,
KNOWLEDGE_SEARCH_TOOL,
CHANGE_CONTEXT_TOOL,
)
TOOLS_BY_NAME = MappingProxyType({tool.name: tool for tool in TOOLS})
TOOL_NAMES = tuple(tool.name for tool in TOOLS)
def tool_declarations() -> list[dict[str, Any]]:
return [tool.declaration() for tool in TOOLS]
+74
View File
@@ -0,0 +1,74 @@
"""Fail-closed identity, policy, and provider resolution for the template server."""
from __future__ import annotations
import os
import sys
from collections.abc import Callable
from dataclasses import dataclass
from typing import Any
from .foundation import IdentityContext, ProjectContextRuntime, ProviderError
from .providers.change import build_provider as build_change_provider
from .providers.issue import build_provider as build_issue_provider
from .providers.knowledge import build_provider as build_knowledge_provider
MINIMUM_PYTHON = (3, 11)
def require_supported_python(version_info: tuple[int, ...] | None = None) -> None:
"""Fail with an actionable message before the MCP server starts."""
current = version_info or tuple(sys.version_info[:3])
if current[:2] < MINIMUM_PYTHON:
raise RuntimeError(
"Project Context MCP requires Python 3.11 or newer; "
f"current runtime is {current[0]}.{current[1]}"
)
@dataclass(frozen=True)
class ProjectScopePolicy:
"""Pilot policy: read scope and exact identity-bound project are both mandatory."""
def decide(self, identity: IdentityContext, tool_name: str, project_id: str) -> bool:
return "read" in identity.granted_scopes and project_id == identity.project
PROVIDER_FACTORIES: dict[str, Callable[[IdentityContext], Any]] = {
"get_project_issue_context": build_issue_provider,
"search_project_knowledge": build_knowledge_provider,
"get_project_change_context": build_change_provider,
}
@dataclass(frozen=True)
class ProjectProviderResolver:
def resolve(self, identity: IdentityContext, tool_name: str) -> Any:
factory = PROVIDER_FACTORIES.get(tool_name)
if factory is None:
raise ProviderError("NOT_FOUND", "The requested tool is not registered.", retryable=False)
return factory(identity)
def _required_environment(name: str) -> str:
value = os.environ.get(name, "").strip()
if not value:
raise RuntimeError(f"Project Context MCP cannot start: required setting {name} is missing")
return value
def default_runtime() -> ProjectContextRuntime:
"""Build immutable runtime state; missing identity configuration fails at boot."""
require_supported_python()
identity = IdentityContext(
actor_id=_required_environment("COWORK_MCP_ACTOR_ID"),
org_unit=_required_environment("COWORK_MCP_ORG_UNIT"),
customer=_required_environment("COWORK_MCP_CUSTOMER"),
project=_required_environment("COWORK_MCP_PROJECT"),
granted_scopes=frozenset({"read"}),
)
return ProjectContextRuntime(
identity=identity,
policy=ProjectScopePolicy(),
credential_resolver=ProjectProviderResolver(),
)
+142
View File
@@ -0,0 +1,142 @@
"""Low-level MCP stdio adapter around the transport-agnostic Project Context core."""
# ruff: noqa: UP045 -- Optional keeps the template importable with Pydantic on Python 3.9.
from __future__ import annotations
import json
from typing import Any, Optional
from uuid import uuid4
from pydantic import ValidationError
from .foundation import (
DispatchResult,
ProjectContextRuntime,
ProviderError,
error_result,
)
from .registry import TOOLS_BY_NAME, tool_declarations
from .runtime import default_runtime, require_supported_python
def dispatch(
name: str,
arguments: dict[str, Any],
runtime: ProjectContextRuntime,
) -> DispatchResult:
"""Validate → authorize → resolve provider → execute → validate output."""
correlation_id = str(uuid4())
tool = TOOLS_BY_NAME.get(name)
if tool is None:
return error_result(
"NOT_FOUND",
category="NOT_FOUND",
retryable=False,
message="The requested MCP tool is not registered.",
suggested_action="Refresh the tool list and choose one of the advertised tools.",
correlation_id=correlation_id,
)
try:
validated_input = tool.input_model.model_validate(arguments or {})
except ValidationError:
return error_result(
"INVALID_INPUT",
category="INVALID_INPUT",
retryable=False,
message="The tool arguments do not match the published input contract.",
suggested_action="Correct the required fields and value bounds, then call again.",
correlation_id=correlation_id,
)
project_id = str(validated_input.project_id)
if not runtime.policy.decide(runtime.identity, name, project_id):
return error_result(
"DENIED",
category="DENIED",
retryable=False,
message="The project is outside the caller's approved scope.",
suggested_action="Use an approved project or ask the project owner for access.",
correlation_id=correlation_id,
)
try:
provider = runtime.credential_resolver.resolve(runtime.identity, name)
raw_output = tool.handler(validated_input, provider)
except ProviderError as exc:
return error_result(
exc.code,
category=exc.code,
retryable=exc.retryable,
message=exc.safe_message,
suggested_action="Check the approved provider configuration and retry if allowed.",
correlation_id=correlation_id,
)
except Exception: # noqa: BLE001 - provider failures must not crash or leak into the agent turn
return error_result(
"UPSTREAM_ERROR",
category="UPSTREAM_ERROR",
retryable=False,
message="The approved provider could not complete the request.",
suggested_action="Check the correlation ID in server logs; do not resend credentials.",
correlation_id=correlation_id,
)
try:
output_with_trace = {**raw_output, "correlation_id": correlation_id}
validated_output = tool.output_model.model_validate(output_with_trace)
except ValidationError:
return error_result(
"UPSTREAM_ERROR",
category="UPSTREAM_ERROR",
retryable=False,
message="The provider response did not match the published output contract.",
suggested_action="Fix the provider mapping before retrying the request.",
correlation_id=correlation_id,
)
return DispatchResult(ok=True, payload=validated_output.model_dump(mode="json"))
def build_server(runtime: Optional[ProjectContextRuntime] = None):
from mcp import types
from mcp.server.lowlevel import Server
require_supported_python()
app_runtime = runtime or default_runtime()
app = Server("project_context")
@app.list_tools()
async def list_tools() -> list[types.Tool]:
return [types.Tool(**declaration) for declaration in tool_declarations()]
@app.call_tool()
async def call_tool(name: str, arguments: dict[str, Any]) -> types.CallToolResult:
result = dispatch(name, arguments or {}, app_runtime)
return types.CallToolResult(
content=[types.TextContent(
type="text",
text=json.dumps(result.payload, ensure_ascii=False, separators=(",", ":")),
)],
structuredContent=result.payload if result.ok else None,
isError=not result.ok,
)
return app
def main() -> None:
import anyio
from mcp.server.stdio import stdio_server
app = build_server()
async def _run() -> None:
async with stdio_server() as (read, write):
await app.run(read, write, app.create_initialization_options())
anyio.run(_run)
if __name__ == "__main__":
main()
@@ -0,0 +1 @@
"""Independent tool modules; ownership is documented in the team guide."""
@@ -0,0 +1,55 @@
"""Member C work package: get_project_change_context."""
# ruff: noqa: UP045 -- Optional keeps Pydantic model evaluation compatible with Python 3.9.
from __future__ import annotations
from typing import Any, Literal, Optional
from pydantic import Field
from ..foundation import ContractModel, SourceCitation, ToolTemplate
class ChangeContextInput(ContractModel):
project_id: str = Field(min_length=1, max_length=128)
change_id: str = Field(min_length=1, max_length=128)
detail: Literal["summary", "standard", "full"] = "standard"
cursor: Optional[str] = Field(default=None, max_length=2048)
class ChangeContextOutput(ContractModel):
correlation_id: str
project_id: str
change_id: str
change_type: Literal["commit", "pull-request", "merge-request"]
title: str
state: str
summary: str
authors: tuple[str, ...]
files: tuple[str, ...]
commits: tuple[str, ...]
related_issues: tuple[str, ...]
source: SourceCitation
truncated: bool
returned: int = Field(ge=0)
remaining: int = Field(ge=0)
next_cursor: Optional[str] = None
def _handle(arguments: ContractModel, provider: Any) -> dict[str, Any]:
request = ChangeContextInput.model_validate(arguments)
return provider.get_change_context(**request.model_dump())
TOOL = ToolTemplate(
name="get_project_change_context",
description=(
"Returns provider-neutral context for one authorized commit, pull request, or merge request "
"with changed files, commits, related issues, and a pinned source. Use when an exact change "
"identifier is known. Do not use for issue details or free-text document search."
),
input_model=ChangeContextInput,
output_model=ChangeContextOutput,
handler=_handle,
)
@@ -0,0 +1,59 @@
"""Member A work package: get_project_issue_context."""
# ruff: noqa: UP045 -- Optional keeps Pydantic model evaluation compatible with Python 3.9.
from __future__ import annotations
from typing import Any, Literal, Optional
from pydantic import Field
from ..foundation import ContractModel, SourceCitation, ToolTemplate
class IssueContextInput(ContractModel):
project_id: str = Field(min_length=1, max_length=128)
issue_key: str = Field(min_length=1, max_length=128)
detail: Literal["summary", "standard", "full"] = "standard"
cursor: Optional[str] = Field(default=None, max_length=2048)
class RelatedItem(ContractModel):
item_id: str
relation: str
title: str
url: str
class IssueContextOutput(ContractModel):
correlation_id: str
project_id: str
issue_key: str
title: str
status: str
description: str
acceptance_criteria: tuple[str, ...]
related: tuple[RelatedItem, ...]
source: SourceCitation
truncated: bool
returned: int = Field(ge=0)
remaining: int = Field(ge=0)
next_cursor: Optional[str] = None
def _handle(arguments: ContractModel, provider: Any) -> dict[str, Any]:
request = IssueContextInput.model_validate(arguments)
return provider.get_issue_context(**request.model_dump())
TOOL = ToolTemplate(
name="get_project_issue_context",
description=(
"Returns one authorized work item's title, state, description, acceptance criteria, "
"related items, and pinned source. Use when an exact issue key is known. Do not use for "
"free-text knowledge search or Git change review."
),
input_model=IssueContextInput,
output_model=IssueContextOutput,
handler=_handle,
)
@@ -0,0 +1,58 @@
"""Member B work package: search_project_knowledge."""
# ruff: noqa: UP045 -- Optional keeps Pydantic model evaluation compatible with Python 3.9.
from __future__ import annotations
from typing import Any, Literal, Optional
from pydantic import Field
from ..foundation import ContractModel, SourceCitation, ToolTemplate
class KnowledgeSearchInput(ContractModel):
project_id: str = Field(min_length=1, max_length=128)
query: str = Field(min_length=2, max_length=1000)
detail: Literal["summary", "standard", "full"] = "standard"
top_k: int = Field(default=5, ge=1, le=20)
language: Optional[Literal["en", "ja", "vi"]] = None
cursor: Optional[str] = Field(default=None, max_length=2048)
class KnowledgeItem(ContractModel):
document_id: str
chunk_id: str
title: str
excerpt: str
score: float = Field(ge=0, le=1)
source: SourceCitation
class KnowledgeSearchOutput(ContractModel):
correlation_id: str
project_id: str
query: str
items: tuple[KnowledgeItem, ...]
truncated: bool
returned: int = Field(ge=0)
remaining: int = Field(ge=0)
next_cursor: Optional[str] = None
def _handle(arguments: ContractModel, provider: Any) -> dict[str, Any]:
request = KnowledgeSearchInput.model_validate(arguments)
return provider.search_knowledge(**request.model_dump())
TOOL = ToolTemplate(
name="search_project_knowledge",
description=(
"Searches approved knowledge for one authorized project and returns ranked excerpts with "
"pinned citations. Use for requirements, design notes, or runbooks when no exact issue is "
"known. Do not use for issue details or Git change review."
),
input_model=KnowledgeSearchInput,
output_model=KnowledgeSearchOutput,
handler=_handle,
)