feat(mcp): add simplified ingest uploads
Add a one-shot IngestManager upload path, an ingest_file_base64 MCP tool, and an authenticated /mcp-ingest/uploads multipart HTTP endpoint so remote agents can transfer files without manual chunk orchestration. Keep uploaded files in runtime staging outside the vault and let wiki-ingest/OpenCode decide archival, registry updates, and index rebuilds. Update service output, docs, and agent rules to make the preferred upload path discoverable while preserving chunked tools as a fallback. Validation: python3 -m unittest discover -v; python3 -m py_compile obsidian_wiki/mcp_ingest.py obsidian_wiki/mcp_server.py scripts/manage_mcp_service.py tests/test_mcp_ingest.py tests/test_mcp_server_remote.py tests/test_mcp_service.py; git diff --check
This commit is contained in:
@@ -167,6 +167,24 @@ class McpIngestTests(unittest.TestCase):
|
||||
self.assertEqual(complete["state"], "complete")
|
||||
self.assertEqual(Path(complete["path"]).read_bytes(), payload)
|
||||
|
||||
def test_create_completed_upload_accepts_bytes_without_agent_chunking(self):
|
||||
payload = b"direct upload payload"
|
||||
|
||||
upload = self.manager.create_completed_upload(
|
||||
file_name="drawing.pdf",
|
||||
payload=payload,
|
||||
project="bjd",
|
||||
doc_type_hint="drawing",
|
||||
)
|
||||
|
||||
self.assertEqual(upload["state"], "complete")
|
||||
self.assertEqual(upload["received_bytes"], len(payload))
|
||||
self.assertEqual(upload["size_bytes"], len(payload))
|
||||
self.assertEqual(upload["sha256"], "sha256:" + self._sha256(payload))
|
||||
self.assertEqual(upload["project"], "bjd")
|
||||
self.assertEqual(upload["doc_type_hint"], "drawing")
|
||||
self.assertEqual(Path(upload["path"]).read_bytes(), payload)
|
||||
|
||||
def test_upload_rejects_unsafe_names_oversized_files_and_large_chunks(self):
|
||||
with self.assertRaises(IngestError):
|
||||
self.manager.create_upload(file_name="../secret.pdf", size_bytes=10, sha256="a" * 64)
|
||||
@@ -182,6 +200,9 @@ class McpIngestTests(unittest.TestCase):
|
||||
data_base64=base64.b64encode(b"x" * 9).decode("ascii"),
|
||||
)
|
||||
|
||||
with self.assertRaises(IngestError):
|
||||
self.manager.create_completed_upload(file_name="too-large.pdf", payload=b"x" * 101)
|
||||
|
||||
def test_start_ingest_job_constructs_restricted_opencode_command(self):
|
||||
payload = b"source data"
|
||||
upload = self._complete_upload("source.pdf", payload)
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import asyncio
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
import unittest
|
||||
@@ -6,6 +9,7 @@ from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
from obsidian_wiki import mcp_server
|
||||
from obsidian_wiki.mcp_ingest import IngestManager
|
||||
|
||||
|
||||
class FakeApp:
|
||||
@@ -32,6 +36,53 @@ def run_asgi_app(app, *, headers=None, scope_type="http"):
|
||||
return messages
|
||||
|
||||
|
||||
def run_asgi_http_request(app, *, method="GET", path="/", headers=None, body=b""):
|
||||
messages = []
|
||||
sent = False
|
||||
scope = {
|
||||
"type": "http",
|
||||
"method": method,
|
||||
"path": path,
|
||||
"raw_path": path.encode("ascii"),
|
||||
"query_string": b"",
|
||||
"headers": headers or [],
|
||||
}
|
||||
|
||||
async def receive():
|
||||
nonlocal sent
|
||||
if sent:
|
||||
return {"type": "http.disconnect"}
|
||||
sent = True
|
||||
return {"type": "http.request", "body": body, "more_body": False}
|
||||
|
||||
async def send(message):
|
||||
messages.append(message)
|
||||
|
||||
asyncio.run(app(scope, receive, send))
|
||||
return messages
|
||||
|
||||
|
||||
def multipart_body(fields, files, boundary="test-boundary"):
|
||||
chunks = []
|
||||
for name, value in fields.items():
|
||||
chunks.append(f"--{boundary}\r\n".encode("ascii"))
|
||||
chunks.append(f'Content-Disposition: form-data; name="{name}"\r\n\r\n'.encode("ascii"))
|
||||
chunks.append(str(value).encode("utf-8"))
|
||||
chunks.append(b"\r\n")
|
||||
for field_name, file_name, content_type, payload in files:
|
||||
chunks.append(f"--{boundary}\r\n".encode("ascii"))
|
||||
chunks.append(
|
||||
(
|
||||
f'Content-Disposition: form-data; name="{field_name}"; filename="{file_name}"\r\n'
|
||||
f"Content-Type: {content_type}\r\n\r\n"
|
||||
).encode("ascii")
|
||||
)
|
||||
chunks.append(payload)
|
||||
chunks.append(b"\r\n")
|
||||
chunks.append(f"--{boundary}--\r\n".encode("ascii"))
|
||||
return b"".join(chunks), boundary
|
||||
|
||||
|
||||
class RemoteMcpServerTests(unittest.TestCase):
|
||||
def test_bearer_token_middleware_accepts_matching_token(self):
|
||||
inner = FakeApp()
|
||||
@@ -111,6 +162,53 @@ class RemoteMcpServerTests(unittest.TestCase):
|
||||
self.assertTrue(fake_server.inner.called)
|
||||
self.assertEqual(messages[0]["status"], 200)
|
||||
|
||||
def test_http_upload_endpoint_accepts_multipart_when_ingest_enabled(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
manager = IngestManager(
|
||||
vault_path=root / "vault",
|
||||
project_root=root / "project",
|
||||
runtime_root=root / "runtime",
|
||||
)
|
||||
app = mcp_server.create_http_app(FakeApp(), "secret-token", ingest_manager=manager)
|
||||
payload = b"uploaded drawing"
|
||||
body, boundary = multipart_body(
|
||||
{"project": "bjd", "doc_type_hint": "drawing", "start_job": "false"},
|
||||
[("files", "drawing.pdf", "application/pdf", payload)],
|
||||
)
|
||||
|
||||
messages = run_asgi_http_request(
|
||||
app,
|
||||
method="POST",
|
||||
path="/mcp-ingest/uploads",
|
||||
headers=[
|
||||
(b"authorization", b"Bearer secret-token"),
|
||||
(b"content-type", f"multipart/form-data; boundary={boundary}".encode("ascii")),
|
||||
],
|
||||
body=body,
|
||||
)
|
||||
|
||||
self.assertEqual(messages[0]["status"], 200)
|
||||
response = b"".join(message.get("body", b"") for message in messages if message["type"] == "http.response.body")
|
||||
data = json.loads(response.decode("utf-8"))
|
||||
self.assertEqual(data["job"], None)
|
||||
self.assertEqual(data["uploads"][0]["state"], "complete")
|
||||
self.assertEqual(data["uploads"][0]["file_name"], "drawing.pdf")
|
||||
self.assertEqual(data["uploads"][0]["sha256"], "sha256:" + hashlib.sha256(payload).hexdigest())
|
||||
|
||||
def test_http_upload_endpoint_requires_ingest_and_bearer_token(self):
|
||||
no_ingest_app = mcp_server.create_http_app(FakeApp(), "secret-token")
|
||||
missing_token = run_asgi_http_request(no_ingest_app, method="POST", path="/mcp-ingest/uploads")
|
||||
self.assertEqual(missing_token[0]["status"], 401)
|
||||
|
||||
disabled = run_asgi_http_request(
|
||||
no_ingest_app,
|
||||
method="POST",
|
||||
path="/mcp-ingest/uploads",
|
||||
headers=[(b"authorization", b"Bearer secret-token")],
|
||||
)
|
||||
self.assertEqual(disabled[0]["status"], 404)
|
||||
|
||||
def test_create_server_uses_file_asset_service_name(self):
|
||||
class FakeMCP:
|
||||
names = []
|
||||
@@ -201,6 +299,59 @@ class RemoteMcpServerTests(unittest.TestCase):
|
||||
self.assertIn("get_ingest_job_result", FakeMCP.tool_names)
|
||||
self.assertIn("cancel_ingest_job", FakeMCP.tool_names)
|
||||
self.assertIn("check_ingest_opencode_readiness", FakeMCP.tool_names)
|
||||
self.assertIn("get_ingest_upload_instructions", FakeMCP.tool_names)
|
||||
self.assertIn("ingest_file_base64", FakeMCP.tool_names)
|
||||
|
||||
def test_ingest_file_base64_tool_uploads_without_chunking(self):
|
||||
class FakeMCP:
|
||||
tools = {}
|
||||
|
||||
def __init__(self, _name, **_kwargs):
|
||||
pass
|
||||
|
||||
def tool(self):
|
||||
def decorator(func):
|
||||
self.tools[func.__name__] = func
|
||||
return func
|
||||
|
||||
return decorator
|
||||
|
||||
def resource(self, *_args, **_kwargs):
|
||||
def decorator(func):
|
||||
return func
|
||||
|
||||
return decorator
|
||||
|
||||
def prompt(self, *_args, **_kwargs):
|
||||
def decorator(func):
|
||||
return func
|
||||
|
||||
return decorator
|
||||
|
||||
with (
|
||||
tempfile.TemporaryDirectory() as tmp,
|
||||
patch.dict("sys.modules", {"mcp.server.fastmcp": type("Mod", (), {"FastMCP": FakeMCP})()}),
|
||||
):
|
||||
root = Path(tmp)
|
||||
mcp_server.create_server(
|
||||
vault_path=root / "vault",
|
||||
enable_ingest=True,
|
||||
project_root=root / "project",
|
||||
ingest_runtime_root=root / "runtime",
|
||||
)
|
||||
payload = b"one shot upload"
|
||||
result = FakeMCP.tools["ingest_file_base64"](
|
||||
file_name="source.pdf",
|
||||
data_base64=base64.b64encode(payload).decode("ascii"),
|
||||
project="bjd",
|
||||
doc_type_hint="drawing",
|
||||
start_job=False,
|
||||
)
|
||||
|
||||
self.assertEqual(result["job"], None)
|
||||
self.assertEqual(result["upload"]["state"], "complete")
|
||||
self.assertEqual(result["upload"]["file_name"], "source.pdf")
|
||||
self.assertEqual(result["upload"]["sha256"], "sha256:" + hashlib.sha256(payload).hexdigest())
|
||||
|
||||
def test_create_server_can_disable_file_asset_tools(self):
|
||||
class FakeMCP:
|
||||
|
||||
@@ -106,6 +106,19 @@ class McpServiceConfigTests(unittest.TestCase):
|
||||
self.assertIn('"wiki-file-assets"', output)
|
||||
self.assertNotIn('"obsidian-wiki"', output)
|
||||
|
||||
def test_render_remote_config_prints_ingest_upload_endpoint_when_enabled(self):
|
||||
output = manage_mcp_service.render_remote_config(
|
||||
hosts=["192.168.1.10", "10.0.0.2"],
|
||||
token="test-token",
|
||||
port=8765,
|
||||
path="/mcp",
|
||||
enabled_tools=("file-assets", "ingest"),
|
||||
)
|
||||
|
||||
self.assertIn("http://192.168.1.10:8765/mcp", output)
|
||||
self.assertIn("http://192.168.1.10:8765/mcp-ingest/uploads", output)
|
||||
self.assertIn("http://10.0.0.2:8765/mcp-ingest/uploads", output)
|
||||
|
||||
def test_new_token_writes_token_without_touching_systemd_when_unit_missing(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
project_root = Path(tmp) / "project"
|
||||
|
||||
Reference in New Issue
Block a user