feat(mcp): improve remote ingest guidance
Make upload-ticket auth the default remote-agent path by returning complete upload URLs and updating service output/docs. Add validate_upload and preview_upload_metadata for lightweight file checks and exact sha256 duplicate warnings before ingest. Expose version, capability schema, file-index freshness, queue state, and known limitations through get_mcp_capabilities. Validation: python3 -m unittest discover -v; python3 -m compileall obsidian_wiki tests scripts; git diff --check.
This commit is contained in:
+155
-1
@@ -10,6 +10,7 @@ import os
|
||||
import re
|
||||
import secrets
|
||||
import shutil
|
||||
import sqlite3
|
||||
import subprocess
|
||||
import time
|
||||
import uuid
|
||||
@@ -18,7 +19,7 @@ from pathlib import Path
|
||||
from threading import RLock
|
||||
from typing import Any
|
||||
|
||||
from obsidian_wiki.file_assets import clean_config_value
|
||||
from obsidian_wiki.file_assets import clean_config_value, db_path_for_vault, registry_path_for_vault
|
||||
|
||||
DEFAULT_INGEST_MAX_FILE_BYTES = 100 * 1024 * 1024
|
||||
DEFAULT_INGEST_MAX_CHUNK_BYTES = 4 * 1024 * 1024
|
||||
@@ -195,6 +196,63 @@ class IngestManager:
|
||||
self._write_json(self._upload_ticket_path(token_hash), meta)
|
||||
return {**self._public_upload_ticket(meta), "upload_token": token}
|
||||
|
||||
def validate_upload_plan(
|
||||
self,
|
||||
files: list[dict[str, Any]],
|
||||
*,
|
||||
project: str | None = None,
|
||||
doc_type_hint: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
if not isinstance(files, list):
|
||||
raise IngestError("files must be a list")
|
||||
global_errors: list[str] = []
|
||||
if not files:
|
||||
global_errors.append("files must not be empty")
|
||||
if len(files) > self.max_files_per_job:
|
||||
global_errors.append(f"too many files for one ingest job: {len(files)} > {self.max_files_per_job}")
|
||||
results = [self._validate_upload_file_plan(item) for item in files]
|
||||
ok = not global_errors and all(not item["errors"] for item in results)
|
||||
return {
|
||||
"ok": ok,
|
||||
"project": self._safe_optional_text(project),
|
||||
"doc_type_hint": self._safe_optional_text(doc_type_hint),
|
||||
"file_count": len(files),
|
||||
"max_file_bytes": self.max_file_bytes,
|
||||
"max_files_per_job": self.max_files_per_job,
|
||||
"errors": global_errors,
|
||||
"files": results,
|
||||
"next_action": "upload_with_ticket" if ok else "fix_errors_before_upload",
|
||||
}
|
||||
|
||||
def preview_upload_metadata(self, upload_ids: list[str]) -> dict[str, Any]:
|
||||
if not upload_ids:
|
||||
raise IngestError("upload_ids must not be empty")
|
||||
if len(upload_ids) > self.max_files_per_job:
|
||||
raise IngestError(f"too many files for one ingest job: {len(upload_ids)} > {self.max_files_per_job}")
|
||||
uploads: list[dict[str, Any]] = []
|
||||
with self._lock:
|
||||
for upload_id in upload_ids:
|
||||
meta = self._load_upload(upload_id)
|
||||
if meta["state"] != "complete":
|
||||
raise IngestError(f"upload is not complete: {upload_id}")
|
||||
public = self._public_upload(meta)
|
||||
duplicates = self._duplicates_for_sha(meta["sha256"])
|
||||
uploads.append(
|
||||
{
|
||||
**public,
|
||||
"file_extension": Path(meta["file_name"]).suffix.lower(),
|
||||
"duplicate_count": len(duplicates),
|
||||
"duplicates": duplicates,
|
||||
"warnings": ["exact sha256 duplicate already exists"] if duplicates else [],
|
||||
}
|
||||
)
|
||||
return {
|
||||
"ok": True,
|
||||
"upload_count": len(uploads),
|
||||
"uploads": uploads,
|
||||
"next_action": "start_ingest_job",
|
||||
}
|
||||
|
||||
def consume_upload_ticket(self, upload_token: str) -> dict[str, Any]:
|
||||
with self._lock:
|
||||
token_hash = self._upload_ticket_hash(upload_token)
|
||||
@@ -597,6 +655,102 @@ class IngestManager:
|
||||
"start_job": bool(meta.get("start_job", True)),
|
||||
}
|
||||
|
||||
def _validate_upload_file_plan(self, item: dict[str, Any]) -> dict[str, Any]:
|
||||
errors: list[str] = []
|
||||
warnings: list[str] = []
|
||||
raw_name = str(item.get("file_name") or "")
|
||||
raw_sha = str(item.get("sha256") or "")
|
||||
file_name = raw_name
|
||||
digest = ""
|
||||
size_bytes: int | None
|
||||
try:
|
||||
file_name = self._validate_file_name(raw_name)
|
||||
except IngestError:
|
||||
errors.append(f"unsafe file name: {raw_name}")
|
||||
try:
|
||||
size_bytes = int(item.get("size_bytes"))
|
||||
except (TypeError, ValueError):
|
||||
size_bytes = None
|
||||
errors.append("size_bytes must be an integer")
|
||||
if size_bytes is not None:
|
||||
if size_bytes < 0:
|
||||
errors.append("size_bytes must be non-negative")
|
||||
if self.max_file_bytes > 0 and size_bytes > self.max_file_bytes:
|
||||
errors.append(f"file exceeds max upload size: {size_bytes} > {self.max_file_bytes}")
|
||||
try:
|
||||
digest = self._normalize_sha256(raw_sha)
|
||||
except IngestError:
|
||||
errors.append("sha256 must be a 64-character hex digest, optionally prefixed with sha256:")
|
||||
duplicates = self._duplicates_for_sha(digest) if digest else []
|
||||
if duplicates:
|
||||
warnings.append("exact sha256 duplicate already exists")
|
||||
status = "error" if errors else "warning" if warnings else "ok"
|
||||
return {
|
||||
"file_name": file_name or raw_name,
|
||||
"size_bytes": size_bytes,
|
||||
"sha256": ("sha256:" + digest) if digest else raw_sha,
|
||||
"file_extension": Path(file_name or raw_name).suffix.lower(),
|
||||
"status": status,
|
||||
"errors": errors,
|
||||
"warnings": warnings,
|
||||
"duplicates": duplicates,
|
||||
"duplicate_count": len(duplicates),
|
||||
}
|
||||
|
||||
def _duplicates_for_sha(self, digest: str) -> list[dict[str, Any]]:
|
||||
normalized = self._normalize_sha256(digest)
|
||||
duplicates: list[dict[str, Any]] = []
|
||||
seen: set[tuple[str, str]] = set()
|
||||
registry = registry_path_for_vault(self.vault)
|
||||
if registry.is_file():
|
||||
for raw in registry.read_text(encoding="utf-8").splitlines():
|
||||
if not raw.strip():
|
||||
continue
|
||||
try:
|
||||
record = json.loads(raw)
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
if str(record.get("source_id") or "").removeprefix("sha256:").lower() != normalized:
|
||||
continue
|
||||
entry = {
|
||||
"source": "source_registry",
|
||||
"source_id": "sha256:" + normalized,
|
||||
"archive_path": record.get("archive_path"),
|
||||
"original_name": record.get("original_name"),
|
||||
}
|
||||
key = (entry["source"], str(entry.get("archive_path") or entry.get("original_name") or ""))
|
||||
if key not in seen:
|
||||
duplicates.append(entry)
|
||||
seen.add(key)
|
||||
db_path = db_path_for_vault(self.vault)
|
||||
if db_path.is_file():
|
||||
try:
|
||||
conn = sqlite3.connect(str(db_path))
|
||||
conn.row_factory = sqlite3.Row
|
||||
rows = conn.execute(
|
||||
"SELECT file_id, archive_path, original_name FROM file_assets WHERE sha256 = ? LIMIT 20",
|
||||
(normalized,),
|
||||
).fetchall()
|
||||
except sqlite3.Error:
|
||||
rows = []
|
||||
finally:
|
||||
try:
|
||||
conn.close()
|
||||
except UnboundLocalError:
|
||||
pass
|
||||
for row in rows:
|
||||
entry = {
|
||||
"source": "file_index",
|
||||
"file_id": row["file_id"],
|
||||
"archive_path": row["archive_path"],
|
||||
"original_name": row["original_name"],
|
||||
}
|
||||
key = (entry["source"], str(entry.get("file_id") or ""))
|
||||
if key not in seen:
|
||||
duplicates.append(entry)
|
||||
seen.add(key)
|
||||
return duplicates
|
||||
|
||||
def _public_job(self, job: dict[str, Any]) -> dict[str, Any]:
|
||||
return {
|
||||
"job_id": job["job_id"],
|
||||
|
||||
+152
-11
@@ -6,13 +6,16 @@ import argparse
|
||||
import json
|
||||
import hmac
|
||||
import os
|
||||
import sqlite3
|
||||
import sys
|
||||
from email import policy
|
||||
from email.parser import BytesParser
|
||||
from fnmatch import fnmatch
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from urllib.parse import urlsplit, urlunsplit
|
||||
|
||||
from obsidian_wiki import __version__
|
||||
from obsidian_wiki.config import config_value, resolve_vault_path
|
||||
from obsidian_wiki.file_assets import clean_config_value, db_path_for_vault, registry_path_for_vault
|
||||
from obsidian_wiki.mcp_ingest import (
|
||||
@@ -54,6 +57,8 @@ DEFAULT_HTTP_PATH = "/mcp"
|
||||
DEFAULT_INGEST_UPLOAD_PATH = "/mcp-ingest/uploads"
|
||||
DEFAULT_TOKEN_ENV = "OBSIDIAN_MCP_TOKEN"
|
||||
MCP_SERVER_NAME = "wiki-file-assets"
|
||||
CAPABILITIES_SCHEMA_VERSION = 1
|
||||
TOOLS_VERSION = 1
|
||||
TOOL_FILE_ASSETS = "file-assets"
|
||||
TOOL_INGEST = "ingest"
|
||||
TOOL_QUERY = "query"
|
||||
@@ -187,6 +192,7 @@ def create_server(
|
||||
host: str = DEFAULT_HTTP_HOST,
|
||||
port: int = DEFAULT_HTTP_PORT,
|
||||
streamable_http_path: str = DEFAULT_HTTP_PATH,
|
||||
public_base_url: str | None = None,
|
||||
allowed_hosts: list[str] | None = None,
|
||||
allowed_origins: list[str] | None = None,
|
||||
enable_file_assets: bool = True,
|
||||
@@ -221,6 +227,8 @@ def create_server(
|
||||
vault = Path(clean_config_value(str(vault_path))).expanduser()
|
||||
db = _resolve_db_path(vault, db_path)
|
||||
project = Path(project_root).expanduser().resolve() if project_root is not None else Path.cwd().resolve()
|
||||
public_base = _normalize_public_base_url(public_base_url or runtime_config_value("OBSIDIAN_MCP_PUBLIC_BASE_URL", ""))
|
||||
public_upload_url = _upload_url_from_public_base(public_base, DEFAULT_INGEST_UPLOAD_PATH)
|
||||
ingest_runtime = (
|
||||
Path(ingest_runtime_root).expanduser().resolve()
|
||||
if ingest_runtime_root is not None
|
||||
@@ -288,13 +296,17 @@ def create_server(
|
||||
)
|
||||
return {
|
||||
"server_name": MCP_SERVER_NAME,
|
||||
"server_version": __version__,
|
||||
"capabilities_schema_version": CAPABILITIES_SCHEMA_VERSION,
|
||||
"tools_version": TOOLS_VERSION,
|
||||
"enabled_tools": enabled,
|
||||
"recommended_first_steps": [
|
||||
"Use ask_wiki for ordinary wiki, business facts, or hybrid questions when query is enabled.",
|
||||
"Use search_file_assets before reading source file resources.",
|
||||
"Use ingest_text_note for short text notes when ingest is enabled.",
|
||||
"Use get_ingest_upload_instructions before HTTP file upload.",
|
||||
"Use create_ingest_upload_ticket before remote HTTP file upload.",
|
||||
],
|
||||
"file_index": _file_index_capabilities(vault, db),
|
||||
"file_assets": {
|
||||
"enabled": enable_file_assets,
|
||||
"tools": (
|
||||
@@ -339,17 +351,35 @@ def create_server(
|
||||
"supports_business_facts": enable_query,
|
||||
"supports_hybrid_questions": enable_query,
|
||||
"public_only_disables_business_facts": True,
|
||||
"supports_structured_result": enable_query,
|
||||
"max_query_chars": query_max_chars,
|
||||
"known_limitations": (
|
||||
[
|
||||
"answer_markdown is produced by the local wiki-query agent; citations and source flags are best-effort structured metadata.",
|
||||
"Long-running queries may return a job_id and require polling get_wiki_query_result.",
|
||||
]
|
||||
if enable_query
|
||||
else []
|
||||
),
|
||||
},
|
||||
"ingest": {
|
||||
"enabled": enable_ingest,
|
||||
"preferred_text_tool": "ingest_text_note" if enable_ingest else None,
|
||||
"http_upload_path": DEFAULT_INGEST_UPLOAD_PATH if enable_ingest else None,
|
||||
"http_upload_url": public_upload_url if enable_ingest else None,
|
||||
"http_upload_url_warning": (
|
||||
None
|
||||
if public_upload_url or not enable_ingest
|
||||
else "Set OBSIDIAN_MCP_PUBLIC_BASE_URL so remote agents can receive a complete upload URL."
|
||||
),
|
||||
"preferred_upload_auth": "upload_ticket" if enable_ingest else None,
|
||||
"tools": (
|
||||
[
|
||||
"get_ingest_upload_instructions",
|
||||
"ingest_text_note",
|
||||
"create_ingest_upload_ticket",
|
||||
"validate_upload",
|
||||
"preview_upload_metadata",
|
||||
"start_ingest_job",
|
||||
"get_ingest_job_status",
|
||||
"get_ingest_job_result",
|
||||
@@ -361,6 +391,17 @@ def create_server(
|
||||
),
|
||||
"max_file_bytes": ingest_max_file_bytes,
|
||||
"max_files_per_job": ingest_max_files_per_job,
|
||||
"last_ingest_at": _last_ingest_at(ingest_manager) if enable_ingest and ingest_manager is not None else None,
|
||||
"queue": _ingest_queue_summary(ingest_manager) if enable_ingest and ingest_manager is not None else None,
|
||||
"known_limitations": (
|
||||
[
|
||||
"Remote file uploads should use single-use upload tickets; bearer upload is retained for local/admin compatibility.",
|
||||
"Upload preview detects exact sha256 duplicates only, not fuzzy near-duplicates.",
|
||||
"Full dry-run ingest is not exposed; OpenCode runs only through the fixed wiki-ingest prompt.",
|
||||
]
|
||||
if enable_ingest
|
||||
else []
|
||||
),
|
||||
},
|
||||
"safety": {
|
||||
"arbitrary_shell": False,
|
||||
@@ -387,32 +428,38 @@ def create_server(
|
||||
@server.tool()
|
||||
def get_ingest_upload_instructions() -> dict[str, Any]:
|
||||
"""Return preferred upload methods and limits for remote MCP ingest clients."""
|
||||
upload_url_warning = (
|
||||
None
|
||||
if public_upload_url
|
||||
else "Set OBSIDIAN_MCP_PUBLIC_BASE_URL so remote agents can receive a complete upload URL."
|
||||
)
|
||||
return {
|
||||
"preferred_method": "use ingest_text_note for short text; POST multipart/form-data files to the HTTP upload endpoint for files",
|
||||
"preferred_method": "use ingest_text_note for short text; for files, call create_ingest_upload_ticket and upload with X-Obsidian-Wiki-Upload-Token",
|
||||
"preferred_upload_auth": "upload_ticket",
|
||||
"http_upload": {
|
||||
"method": "POST",
|
||||
"path": DEFAULT_INGEST_UPLOAD_PATH,
|
||||
"url": public_upload_url,
|
||||
"url_warning": upload_url_warning,
|
||||
"file_field": "files",
|
||||
"auth": (
|
||||
"use the same Authorization: Bearer <token> header as the MCP endpoint, "
|
||||
"or call create_ingest_upload_ticket and send X-Obsidian-Wiki-Upload-Token"
|
||||
),
|
||||
"auth": "call create_ingest_upload_ticket and send X-Obsidian-Wiki-Upload-Token",
|
||||
"bearer_auth": "admin_or_local_only",
|
||||
"optional_fields": ["project", "doc_type_hint", "note", "start_job"],
|
||||
"start_job_default": True,
|
||||
"curl_example": (
|
||||
"curl -H 'Authorization: Bearer <token>' "
|
||||
"curl -H 'X-Obsidian-Wiki-Upload-Token: <upload-token>' "
|
||||
"-F 'files=@drawing.pdf' -F 'project=bjd' "
|
||||
"-F 'doc_type_hint=drawing' -F 'start_job=true' "
|
||||
"http://<host>:<port>/mcp-ingest/uploads"
|
||||
f"{public_upload_url or '<upload-url>'}"
|
||||
),
|
||||
},
|
||||
"upload_ticket_tool": {
|
||||
"name": "create_ingest_upload_ticket",
|
||||
"token_header": "X-Obsidian-Wiki-Upload-Token",
|
||||
"best_for": "remote agents that can run curl but cannot read the main MCP bearer token",
|
||||
"best_for": "default file upload path for remote agents",
|
||||
"curl_example": (
|
||||
"curl -H 'X-Obsidian-Wiki-Upload-Token: <upload-token>' "
|
||||
"-F 'files=@drawing.pdf' http://<host>:<port>/mcp-ingest/uploads"
|
||||
f"-F 'files=@drawing.pdf' {public_upload_url or '<upload-url>'}"
|
||||
),
|
||||
},
|
||||
"direct_text_tool": {
|
||||
@@ -429,6 +476,12 @@ def create_server(
|
||||
"staging": {
|
||||
"note": "uploads are temporary staging files outside the vault; wiki-ingest decides final archive/index placement",
|
||||
},
|
||||
"recommended_file_workflow": [
|
||||
"create_ingest_upload_ticket(start_job=false)",
|
||||
"POST multipart files with X-Obsidian-Wiki-Upload-Token",
|
||||
"preview_upload_metadata(upload_ids)",
|
||||
"start_ingest_job(upload_ids) when preview looks correct",
|
||||
],
|
||||
}
|
||||
|
||||
@server.tool()
|
||||
@@ -472,15 +525,35 @@ def create_server(
|
||||
return {
|
||||
**ticket,
|
||||
"upload_path": DEFAULT_INGEST_UPLOAD_PATH,
|
||||
"upload_url": public_upload_url,
|
||||
"upload_url_warning": (
|
||||
None
|
||||
if public_upload_url
|
||||
else "Set OBSIDIAN_MCP_PUBLIC_BASE_URL so remote agents can receive a complete upload URL."
|
||||
),
|
||||
"token_header": "X-Obsidian-Wiki-Upload-Token",
|
||||
"expires_seconds_max": MAX_UPLOAD_TICKET_SECONDS,
|
||||
"curl_example": (
|
||||
"curl -H 'X-Obsidian-Wiki-Upload-Token: "
|
||||
+ ticket["upload_token"]
|
||||
+ "' -F 'files=@/path/to/file.pdf' http://<host>:<port>/mcp-ingest/uploads"
|
||||
+ f"' -F 'files=@/path/to/file.pdf' {public_upload_url or '<upload-url>'}"
|
||||
),
|
||||
}
|
||||
|
||||
@server.tool()
|
||||
def validate_upload(
|
||||
files: list[dict[str, Any]],
|
||||
project: str | None = None,
|
||||
doc_type_hint: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Validate a planned remote upload without creating files or starting ingest."""
|
||||
return ingest_manager.validate_upload_plan(files, project=project, doc_type_hint=doc_type_hint)
|
||||
|
||||
@server.tool()
|
||||
def preview_upload_metadata(upload_ids: list[str]) -> dict[str, Any]:
|
||||
"""Preview completed upload metadata and exact duplicate warnings before ingest."""
|
||||
return ingest_manager.preview_upload_metadata(upload_ids)
|
||||
|
||||
@server.tool()
|
||||
def start_ingest_job(upload_ids: list[str], note: str | None = None) -> dict[str, Any]:
|
||||
"""Start or queue a local OpenCode wiki-ingest job for completed uploads."""
|
||||
@@ -1200,6 +1273,74 @@ def _resolve_db_path(vault: Path, raw_path: str | Path | None) -> Path:
|
||||
return db_path
|
||||
|
||||
|
||||
def _normalize_public_base_url(raw_url: str | None) -> str:
|
||||
value = clean_config_value(str(raw_url or "")).strip().rstrip("/")
|
||||
if not value:
|
||||
return ""
|
||||
parsed = urlsplit(value)
|
||||
if not parsed.scheme or not parsed.netloc:
|
||||
return ""
|
||||
return urlunsplit((parsed.scheme, parsed.netloc, parsed.path.rstrip("/"), "", ""))
|
||||
|
||||
|
||||
def _upload_url_from_public_base(public_base_url: str, upload_path: str) -> str | None:
|
||||
if not public_base_url:
|
||||
return None
|
||||
parsed = urlsplit(public_base_url)
|
||||
return urlunsplit((parsed.scheme, parsed.netloc, upload_path, "", ""))
|
||||
|
||||
|
||||
def _file_index_capabilities(vault: Path, db: Path) -> dict[str, Any]:
|
||||
registry = registry_path_for_vault(vault)
|
||||
record_count: int | None = None
|
||||
if db.is_file():
|
||||
try:
|
||||
conn = sqlite3.connect(str(db))
|
||||
record_count = int(conn.execute("SELECT COUNT(*) FROM file_assets").fetchone()[0])
|
||||
except sqlite3.Error:
|
||||
record_count = None
|
||||
finally:
|
||||
try:
|
||||
conn.close()
|
||||
except UnboundLocalError:
|
||||
pass
|
||||
return {
|
||||
"exists": db.is_file(),
|
||||
"registry_exists": registry.is_file(),
|
||||
"record_count": record_count,
|
||||
"last_rebuild_at": _path_mtime_iso(db) if db.is_file() else None,
|
||||
}
|
||||
|
||||
|
||||
def _path_mtime_iso(path: Path) -> str | None:
|
||||
try:
|
||||
from datetime import datetime, timezone
|
||||
|
||||
return datetime.fromtimestamp(path.stat().st_mtime, tz=timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
|
||||
def _ingest_queue_summary(manager: IngestManager) -> dict[str, int]:
|
||||
jobs = manager._iter_jobs()
|
||||
return {
|
||||
"queued": sum(1 for job in jobs if job.get("state") == "queued"),
|
||||
"running": sum(1 for job in jobs if job.get("state") == "running"),
|
||||
"terminal": sum(1 for job in jobs if job.get("state") in {"succeeded", "failed", "cancelled"}),
|
||||
}
|
||||
|
||||
|
||||
def _last_ingest_at(manager: IngestManager) -> str | None:
|
||||
timestamps = []
|
||||
for job in manager._iter_jobs():
|
||||
for key in ("finished_at", "started_at", "created_at"):
|
||||
value = str(job.get(key) or "")
|
||||
if value:
|
||||
timestamps.append(value)
|
||||
break
|
||||
return max(timestamps) if timestamps else None
|
||||
|
||||
|
||||
def _as_mcp_results(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
return [_as_mcp_result(row) for row in rows]
|
||||
|
||||
|
||||
Reference in New Issue
Block a user