mirror of
https://github.com/dnlbauer/cordra-mcp.git
synced 2026-09-10 21:55:30 +00:00
Compare commits
15 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d42bb1a581 | ||
|
|
c3b202c998 | ||
|
|
0bee7f2775 | ||
|
|
adc24dd4ad | ||
|
|
99fdaadea6 | ||
|
|
8b0694dff1 | ||
|
|
ea9cf92b2c | ||
|
|
3c8367f804 | ||
|
|
0a9ba538ef | ||
|
|
eaa300b8c2 | ||
|
|
7b77186ced | ||
|
|
5451883739 | ||
|
|
7d74d8d9af | ||
|
|
f6bfb14b29 | ||
|
|
9c9594367c |
@@ -1,5 +1,7 @@
|
||||
FROM python:3.13-alpine
|
||||
|
||||
EXPOSE 8000
|
||||
|
||||
# Install package manager
|
||||
COPY --from=ghcr.io/astral-sh/uv:latest /uv /uvx /bin/
|
||||
|
||||
@@ -18,4 +20,6 @@ COPY src src
|
||||
RUN uv sync \
|
||||
--locked
|
||||
|
||||
ENV CORDRA_RUN_MODE=http
|
||||
|
||||
CMD ["uv", "run", "cordra-mcp"]
|
||||
|
||||
24
README.md
24
README.md
@@ -26,24 +26,44 @@ ensuring safe exploration without risk of data modification or corruption.
|
||||
|
||||
### Tools
|
||||
|
||||
- `get_object` - Retrieve a digital object by its complete ID/handle.
|
||||
- `object_id` - Complete object ID (e.g., "test/abc123")
|
||||
- `search_objects` - Search for digital objects using a query string with pagination support.
|
||||
- `query` - Lucene/Solr compatible search query
|
||||
- `type` - Optional filter by object type
|
||||
- `limit` - Number of results per page (default: 1)
|
||||
- `limit` - Number of results per page (default: 25)
|
||||
- `page_num` - Page number to retrieve, 0-based (default: 0)
|
||||
- `count_objects` - Count the total number of objects matching a query.
|
||||
- `query` - Lucene/Solr compatible search query
|
||||
- `type` - Optional filter by object type
|
||||
|
||||
#### Query Syntax
|
||||
|
||||
**CRITICAL**: JSON properties MUST be prefixed with `/`
|
||||
|
||||
✅ **Correct Examples:**
|
||||
- `/title:*report*` - Wildcard search in title field
|
||||
- `/author/name:Daniel` - Nested property access
|
||||
- `/status:active AND /priority:high` - Boolean operators
|
||||
- Use `type` parameter instead of including `type:` in query
|
||||
|
||||
❌ **Wrong (will fail):**
|
||||
- `name:John` - Missing `/` prefix
|
||||
- `author/name:Daniel` - Missing leading `/`
|
||||
- `type:Person` - Use the `type` parameter instead
|
||||
|
||||
**Operators:** `*` (wildcard), `?` (single char), `AND`, `OR`, `NOT`, `"phrases"`
|
||||
|
||||
## Configuration
|
||||
|
||||
The MCP server can be configured using environment variables with the `CORDRA_` prefix:
|
||||
The MCP server can be configured using environment variables:
|
||||
|
||||
- `CORDRA_BASE_URL` - Cordra server URL (default: `https://localhost:8443`)
|
||||
- `CORDRA_USERNAME` - Username for authentication (optional)
|
||||
- `CORDRA_PASSWORD` - Password for authentication (optional)
|
||||
- `CORDRA_VERIFY_SSL` - SSL certificate verification (default: `true`)
|
||||
- `CORDRA_TIMEOUT` - Request timeout in seconds (default: `30`)
|
||||
- `LOGLEVEL` - Logging level (default: `INFO`, options: `DEBUG`, `INFO`, `WARNING`, `ERROR`, `CRITICAL`)
|
||||
|
||||
## Usage
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[project]
|
||||
name = "cordra-mcp"
|
||||
version = "1.2.0"
|
||||
version = "1.3.2"
|
||||
description = "MCP server for Cordra digital object repository"
|
||||
authors = [
|
||||
{name = "Daniel Bauer", email = "github@dbauer.me"},
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
"""MCP server for Cordra digital object repository."""
|
||||
|
||||
__version__ = "1.2.0"
|
||||
__version__ = "1.3.2"
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
"""Configuration settings for the MCP Cordra server."""
|
||||
|
||||
from pydantic import Field
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import Field, field_validator
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
|
||||
@@ -16,6 +18,10 @@ class CordraConfig(BaseSettings):
|
||||
default="https://localhost:8443",
|
||||
description="Base URL of the Cordra repository",
|
||||
)
|
||||
host: str = Field(
|
||||
default="0.0.0.0",
|
||||
description="The host under which the MCP server runs when deployed as http run_mode",
|
||||
)
|
||||
username: str | None = Field(
|
||||
default=None, description="Username for Cordra authentication"
|
||||
)
|
||||
@@ -26,3 +32,24 @@ class CordraConfig(BaseSettings):
|
||||
default=True, description="Whether to verify SSL certificates"
|
||||
)
|
||||
timeout: int = Field(default=30, description="Request timeout in seconds")
|
||||
run_mode: Literal["stdio", "http"] | None = Field(
|
||||
default="stdio", description="Run mode for the MCP client"
|
||||
)
|
||||
log_level: str = Field(
|
||||
default="INFO",
|
||||
description="Logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL)",
|
||||
validation_alias="LOGLEVEL",
|
||||
)
|
||||
|
||||
@field_validator("log_level", mode="before")
|
||||
@classmethod
|
||||
def validate_log_level(cls, v: str) -> str:
|
||||
"""Validate that log_level is a standard logging level."""
|
||||
level_str = str(v).upper().strip()
|
||||
valid_levels = {"DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"}
|
||||
|
||||
if level_str not in valid_levels:
|
||||
raise ValueError(
|
||||
f"Invalid log level '{v}'. Must be one of: {', '.join(valid_levels)}"
|
||||
)
|
||||
return level_str
|
||||
|
||||
@@ -7,6 +7,7 @@ import logging
|
||||
from mcp.server.fastmcp import FastMCP
|
||||
from mcp.server.fastmcp.resources import FunctionResource
|
||||
|
||||
from . import __version__
|
||||
from .client import (
|
||||
CordraAuthenticationError,
|
||||
CordraClient,
|
||||
@@ -16,37 +17,39 @@ from .client import (
|
||||
from .config import CordraConfig
|
||||
|
||||
# Initialize the MCP server
|
||||
mcp = FastMCP("cordra-mcp")
|
||||
config = CordraConfig()
|
||||
mcp = FastMCP("cordra-mcp", host=config.host, port=8000)
|
||||
|
||||
# Initialize Cordra client at startup
|
||||
config = CordraConfig()
|
||||
cordra_client = CordraClient(config)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
logger.setLevel(config.log_level)
|
||||
|
||||
|
||||
@mcp.tool(
|
||||
name="search_objects",
|
||||
title="Search Cordra Objects",
|
||||
description="""Search for digital objects in the Cordra repository using Lucene/Solr query syntax.
|
||||
description="""Search for digital objects using Lucene/Solr query syntax.
|
||||
|
||||
Examples:
|
||||
- /title:report - Find objects with 'report' in title
|
||||
- /author:smith - Find objects by author Smith
|
||||
- /name:John AND type:Person - Complex queries
|
||||
CRITICAL SYNTAX RULES:
|
||||
1. Properties MUST start with '/' - Example: /title:report
|
||||
2. Nested properties: /parent/child:value
|
||||
3. Use 'type' parameter - NEVER 'type:' in query
|
||||
4. Operators: * ? AND OR NOT "phrases"
|
||||
|
||||
Pagination:
|
||||
- Results are paginated with 0-based page numbering
|
||||
- Use 'limit' to control page size (default: 25)
|
||||
- Use 'page_num' to specify which page to retrieve (default: 0)
|
||||
✅ CORRECT:
|
||||
- /title:*report* /author/name:Daniel
|
||||
- /status:active AND /priority:high
|
||||
- query="/title:report", type="Document"
|
||||
|
||||
Returns a JSON object containing:
|
||||
- object_ids: List of object IDs that match the search
|
||||
- total_count: Total number of objects matching the query
|
||||
- page_num: Current page number
|
||||
- page_size: Number of results per page
|
||||
❌ WRONG:
|
||||
- name:John (missing /)
|
||||
- author/name:Daniel (missing /)
|
||||
- type:Person (use type parameter)
|
||||
|
||||
Use the cordra://objects/{prefix}/{suffix} resources to retrieve full object details.""",
|
||||
Returns: {results: [ids], total_count, page_num, page_size}
|
||||
Pagination: limit (default 25), page_num (0-based)""",
|
||||
)
|
||||
async def search_objects(
|
||||
query: str,
|
||||
@@ -57,10 +60,9 @@ async def search_objects(
|
||||
"""Search for digital objects in the Cordra repository with pagination support.
|
||||
|
||||
Args:
|
||||
query: The search query string (Lucene/Solr compatible). Examples:
|
||||
- "/title:report" - Find objects with "report" in title
|
||||
- "/author:smith" - Find objects by author Smith
|
||||
- "/name:John AND type:Person" - Complex queries
|
||||
query: Search query (Lucene/Solr). Properties MUST start with '/'.
|
||||
✅ CORRECT: /title:*report*, /author/name:Daniel
|
||||
❌ WRONG: name:John, author/name:Daniel, type:Person
|
||||
type: Optional filter by object type (e.g., "Person", "Document", "Project")
|
||||
limit: Page size - number of results per page (default: 25)
|
||||
page_num: Page number to retrieve, 0-based (default: 0 for first page)
|
||||
@@ -94,7 +96,8 @@ async def search_objects(
|
||||
|
||||
Examples:
|
||||
- /title:report - Count objects with 'report' in title
|
||||
- /author:smith - Count objects by author Smith
|
||||
- type:Person - Find all Persons. Note that "type" is special and uses no slash "/"
|
||||
- /author/name:Daniel - Find objects with author Daniel as nested property.
|
||||
- /name:John AND type:Person - Complex queries
|
||||
|
||||
Returns the count of objects as integer.
|
||||
@@ -107,10 +110,9 @@ async def count_objects(
|
||||
"""Count digital objects in the Cordra repository matching a search query.
|
||||
|
||||
Args:
|
||||
query: The search query string (Lucene/Solr compatible). Examples:
|
||||
- "/title:report" - Count objects with "report" in title
|
||||
- "/author:smith" - Count objects by author Smith
|
||||
- "/name:John AND type:Person" - Complex queries
|
||||
query: Search query (Lucene/Solr). Properties MUST start with '/'.
|
||||
✅ CORRECT: /title:*report*, /author/name:Daniel
|
||||
❌ WRONG: name:John, author/name:Daniel, type:Person
|
||||
type: Optional filter by object type (e.g., "Person", "Document", "Project")
|
||||
|
||||
Returns:
|
||||
@@ -132,6 +134,41 @@ async def count_objects(
|
||||
raise RuntimeError(f"Count failed: {e}") from e
|
||||
|
||||
|
||||
@mcp.tool(
|
||||
name="get_object",
|
||||
title="Get Cordra Object by ID",
|
||||
description="""Retrieve a digital object by its complete ID/handle.
|
||||
|
||||
Returns: Full object with metadata as JSON
|
||||
Example: get_object("test/abc123")""",
|
||||
)
|
||||
async def get_object(object_id: str) -> str:
|
||||
"""Retrieve a Cordra digital object by its complete ID.
|
||||
|
||||
Args:
|
||||
object_id: The complete object ID/handle (e.g., "test/abc123" or "wildlive/7a4b7b65f8bb155ad36d")
|
||||
|
||||
Returns:
|
||||
JSON string containing the complete digital object with all metadata
|
||||
|
||||
Raises:
|
||||
RuntimeError: If the object is not found or there's an API error
|
||||
"""
|
||||
try:
|
||||
digital_object = await cordra_client.get_object(object_id)
|
||||
object_dict = digital_object.model_dump()
|
||||
return json.dumps(object_dict, indent=2)
|
||||
|
||||
except ValueError as e:
|
||||
raise RuntimeError(f"Invalid object ID: {e}") from e
|
||||
except CordraNotFoundError as e:
|
||||
raise RuntimeError(f"Object not found: {object_id}") from e
|
||||
except CordraAuthenticationError as e:
|
||||
raise RuntimeError(f"Authentication failed: {e}") from e
|
||||
except CordraClientError as e:
|
||||
raise RuntimeError(f"Failed to retrieve object {object_id}: {e}") from e
|
||||
|
||||
|
||||
@mcp.resource(
|
||||
"cordra://objects/{prefix}/{suffix}",
|
||||
name="cordra-object",
|
||||
@@ -267,15 +304,18 @@ async def register_schema_resources() -> None:
|
||||
|
||||
async def initialize_server() -> None:
|
||||
"""Initialize server resources before starting."""
|
||||
logger.info("Initializing Cordra MCP server...")
|
||||
logger.info(f"Initializing Cordra MCP server v{__version__}...")
|
||||
await register_schema_resources()
|
||||
logger.info("Server initialization complete")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""Main entry point for the MCP server."""
|
||||
if config.run_mode == "stdio":
|
||||
asyncio.run(initialize_server())
|
||||
mcp.run()
|
||||
else:
|
||||
mcp.run(transport="streamable-http")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -16,6 +16,7 @@ from cordra_mcp.server import (
|
||||
count_objects,
|
||||
get_cordra_design,
|
||||
get_cordra_object,
|
||||
get_object,
|
||||
search_objects,
|
||||
)
|
||||
|
||||
@@ -162,6 +163,67 @@ class TestGetCordraObject:
|
||||
assert parsed_result["payloads"] is None
|
||||
|
||||
|
||||
class TestGetObject:
|
||||
"""Test the get_object tool."""
|
||||
|
||||
@patch("cordra_mcp.server.cordra_client")
|
||||
async def test_get_object_success(
|
||||
self, mock_client: Any, sample_digital_object: DigitalObject
|
||||
) -> None:
|
||||
"""Test successful object retrieval with complete ID."""
|
||||
mock_client.get_object = AsyncMock(return_value=sample_digital_object)
|
||||
|
||||
result = await get_object("people/john-doe-123")
|
||||
|
||||
# Verify the result is valid JSON
|
||||
parsed_result = json.loads(result)
|
||||
assert parsed_result["id"] == "people/john-doe-123"
|
||||
assert parsed_result["type"] == "Person"
|
||||
assert parsed_result["content"]["name"] == "John Doe"
|
||||
|
||||
# Verify the client was called with the correct object ID
|
||||
mock_client.get_object.assert_called_once_with("people/john-doe-123")
|
||||
|
||||
@patch("cordra_mcp.server.cordra_client")
|
||||
async def test_get_object_not_found(self, mock_client: Any) -> None:
|
||||
"""Test object not found exception."""
|
||||
mock_client.get_object = AsyncMock(
|
||||
side_effect=CordraNotFoundError("Object not found: test/nonexistent")
|
||||
)
|
||||
|
||||
with pytest.raises(RuntimeError) as exc_info:
|
||||
await get_object("test/nonexistent")
|
||||
|
||||
assert "Object not found: test/nonexistent" in str(exc_info.value)
|
||||
mock_client.get_object.assert_called_once_with("test/nonexistent")
|
||||
|
||||
@patch("cordra_mcp.server.cordra_client")
|
||||
async def test_get_object_client_error(self, mock_client: Any) -> None:
|
||||
"""Test general client error handling."""
|
||||
mock_client.get_object = AsyncMock(
|
||||
side_effect=CordraClientError("Connection failed")
|
||||
)
|
||||
|
||||
with pytest.raises(RuntimeError) as exc_info:
|
||||
await get_object("test/obj123")
|
||||
|
||||
assert "Failed to retrieve object test/obj123" in str(exc_info.value)
|
||||
mock_client.get_object.assert_called_once_with("test/obj123")
|
||||
|
||||
@patch("cordra_mcp.server.cordra_client")
|
||||
async def test_get_object_authentication_error(self, mock_client: Any) -> None:
|
||||
"""Test authentication error handling."""
|
||||
mock_client.get_object = AsyncMock(
|
||||
side_effect=CordraAuthenticationError("Authentication failed")
|
||||
)
|
||||
|
||||
with pytest.raises(RuntimeError) as exc_info:
|
||||
await get_object("test/obj123")
|
||||
|
||||
assert "Authentication failed" in str(exc_info.value)
|
||||
mock_client.get_object.assert_called_once_with("test/obj123")
|
||||
|
||||
|
||||
class TestSchemaResourceFunctions:
|
||||
"""Test the schema resource functions."""
|
||||
|
||||
@@ -464,6 +526,39 @@ class TestSearchObjects:
|
||||
"nonexistent:data", object_type=None, page_size=25, page_num=0
|
||||
)
|
||||
|
||||
@patch("cordra_mcp.server.cordra_client")
|
||||
async def test_search_objects_with_slash_prefixed_properties(
|
||||
self, mock_client: Any
|
||||
) -> None:
|
||||
"""Test object search with correct slash-prefixed property syntax."""
|
||||
mock_search_result = {
|
||||
"results": [
|
||||
{
|
||||
"id": "reports/2024-annual",
|
||||
"type": "Document",
|
||||
"content": {"title": "Annual Report 2024"},
|
||||
},
|
||||
],
|
||||
"total_size": 1,
|
||||
"page_num": 0,
|
||||
"page_size": 25,
|
||||
}
|
||||
mock_client.find = AsyncMock(return_value=mock_search_result)
|
||||
|
||||
# Test with slash-prefixed property and nested property
|
||||
result = await search_objects("/title:*report* AND /author/name:Daniel")
|
||||
|
||||
parsed_result = json.loads(result)
|
||||
assert parsed_result["results"] == ["reports/2024-annual"]
|
||||
assert parsed_result["total_count"] == 1
|
||||
|
||||
mock_client.find.assert_called_once_with(
|
||||
"/title:*report* AND /author/name:Daniel",
|
||||
object_type=None,
|
||||
page_size=25,
|
||||
page_num=0,
|
||||
)
|
||||
|
||||
@patch("cordra_mcp.server.cordra_client")
|
||||
async def test_search_objects_client_error(self, mock_client: Any) -> None:
|
||||
"""Test object search with client error."""
|
||||
|
||||
Reference in New Issue
Block a user