File size: 12,750 Bytes
f991fa0
 
 
 
a5a2c66
f991fa0
a5a2c66
f991fa0
 
3777688
f991fa0
b9ce5b6
 
f991fa0
 
3777688
 
 
f991fa0
bc6b6db
bc942ec
bc6b6db
 
 
 
 
f991fa0
a5a2c66
 
f991fa0
 
25a8f4d
 
b9a4f82
 
25a8f4d
 
b9a4f82
25a8f4d
f991fa0
 
 
 
bc6b6db
f991fa0
 
f526a54
 
bc942ec
c5b6c1c
 
 
 
fe77afe
c5b6c1c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f26568c
 
 
 
 
 
c5b6c1c
 
 
 
 
 
 
 
bc942ec
 
f991fa0
 
bc6b6db
 
 
 
 
 
 
 
8378c97
 
bc6b6db
8378c97
 
 
bc6b6db
8378c97
bc6b6db
 
 
 
 
 
 
 
 
 
 
f991fa0
 
 
 
 
 
 
 
 
 
 
 
3777688
 
 
 
f991fa0
 
 
25a8f4d
f991fa0
 
a5a2c66
f991fa0
3777688
f991fa0
3777688
a5a2c66
 
 
 
 
 
 
 
3777688
 
a5a2c66
3777688
f991fa0
 
 
 
 
 
 
 
 
 
031eb89
f991fa0
3777688
 
 
bc942ec
a5a2c66
f991fa0
3777688
f991fa0
3777688
a5a2c66
 
 
 
 
 
 
3777688
 
a5a2c66
3777688
bc942ec
 
 
 
 
 
 
 
e543f30
2e98ac7
e543f30
 
d5805ba
e543f30
d5805ba
 
e543f30
 
f991fa0
 
 
 
 
 
 
3777688
 
 
25a8f4d
f991fa0
 
25a8f4d
f991fa0
 
 
25a8f4d
f991fa0
531624f
a5a2c66
f991fa0
3777688
f991fa0
 
 
 
 
 
 
 
3777688
a5a2c66
 
 
 
 
 
 
3777688
 
a5a2c66
3777688
531624f
 
 
 
 
 
 
 
e543f30
 
 
 
d5805ba
e543f30
d5805ba
 
e543f30
 
f991fa0
 
 
 
3777688
 
 
f991fa0
a5a2c66
f991fa0
3777688
f991fa0
 
3777688
a5a2c66
 
 
 
 
 
 
3777688
 
a5a2c66
3777688
f991fa0
 
 
bc942ec
 
 
b9ce5b6
 
 
 
 
bc942ec
 
 
 
b9ce5b6
bc942ec
f991fa0
bc942ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b9ce5b6
 
e543f30
 
 
 
 
 
 
b9ce5b6
3777688
f991fa0
 
3777688
 
 
f991fa0
3777688
 
 
f991fa0
 
 
 
 
 
 
 
 
 
 
 
 
3777688
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
"""FastMCP server exposing vault and indexing tools."""

from __future__ import annotations

import logging
import os
import time
from typing import Any, Dict, List, Optional

from dotenv import load_dotenv
from fastmcp import FastMCP
from fastmcp.tools.tool import ToolResult
from mcp.types import TextContent
from pydantic import Field

# Load environment variables from .env file
load_dotenv()

from ..services import IndexerService, VaultNote, VaultService
from ..services.auth import AuthError, AuthService
from ..services.config import get_config, PROJECT_ROOT

try:
    from fastmcp.server.http import _current_http_request  # type: ignore
except ImportError:  # pragma: no cover
    _current_http_request = None

logger = logging.getLogger(__name__)

mcp = FastMCP(
    "obsidian-docs-viewer",
    instructions=(
        "Multi-tenant vault tools. STDIO uses user_id 'local-dev'; HTTP mode must validate each "
        "request with JWT.sub. Note paths must be relative '.md' files under 256 chars without '..' or '\\'. "
        "Frontmatter is YAML: tags are string arrays and 'version' is reserved. Notes must be <=1 MiB; "
        "writes refresh created/updated timestamps and synchronously update the search index; deletes "
        "clear index rows and backlinks. Wikilinks use [[...]] slug matching (prefer same folder, else "
        "lexicographic). Search ranking = bm25(title*3, body*1) + recency bonus (+1 if <=7d, +0.5 if <=30d)."
    ),
)

vault_service = VaultService()
indexer_service = IndexerService()
auth_service = AuthService()


@mcp.resource("ui://widget/note.html", mime_type="text/html+skybridge")
def widget_resource() -> str:
    """Return the widget HTML bundle."""
    # Locate widget.html relative to project root
    # In Docker: /app/frontend/dist/widget.html
    # Local: frontend/dist/widget.html
    # We use PROJECT_ROOT from config
    
    widget_path = PROJECT_ROOT / "frontend" / "dist" / "widget.html"
    
    logger.info(f"Reading widget from: {widget_path}")
    
    if not widget_path.exists():
        logger.error(f"Widget path does not exist: {widget_path}")
        return "Widget build not found. Please run 'npm run build' in frontend directory."
        
    try:
        html_content = widget_path.read_text(encoding="utf-8")
        logger.info(f"Widget content length: {len(html_content)}")
        if not html_content.strip():
            logger.error("Widget file is empty!")
            return "Widget build file is empty."
            
        # Replace relative asset paths with absolute URLs for ChatGPT iframe
        config = get_config()
        base_url = config.hf_space_url.rstrip("/")
        logger.info(f"Injecting base URL: {base_url}")
        
        # Inject API_BASE_URL global for the widget to use
        html_content = html_content.replace(
            '<head>', 
            f'<head><script>window.API_BASE_URL = "{base_url}";</script>'
        )
        
        # Vite builds usually output /assets/...
        html_content = html_content.replace('src="/assets/', f'src="{base_url}/assets/')
        html_content = html_content.replace('href="/assets/', f'href="{base_url}/assets/')
        
        return html_content
    except Exception as e:
        logger.exception(f"Failed to read widget file: {e}")
        return f"Server error reading widget: {e}"


def _current_user_id() -> str:
    """Resolve the acting user ID (local mode defaults to local-dev)."""
    # HTTP transport (hosted) uses Authorization headers
    if _current_http_request is not None:
        try:
            request = _current_http_request.get()  # type: ignore[call-arg]
        except LookupError:
            request = None
        if request is not None:
            header = request.headers.get("Authorization")
            
            # Check for No-Auth mode if header is missing
            if not header:
                config = get_config()
                if config.enable_noauth_mcp:
                    return "demo-user"
                raise PermissionError("Authorization header required")
                
            scheme, _, token = header.partition(" ")
            if scheme.lower() != "bearer" or not token:
                raise PermissionError("Authorization header must be 'Bearer <token>'")
            try:
                payload = auth_service.validate_jwt(token)
            except AuthError as exc:
                raise PermissionError(exc.message) from exc
            os.environ.setdefault("LOCAL_USER_ID", payload.sub)
            return payload.sub

    # STDIO / local fall back
    return os.getenv("LOCAL_USER_ID", "local-dev")


def _note_to_response(note: VaultNote) -> Dict[str, Any]:
    return {
        "path": note["path"],
        "title": note["title"],
        "metadata": dict(note.get("metadata") or {}),
        "body": note.get("body", ""),
    }


@mcp.tool(
    name="list_notes",
    description="List notes in the vault (optionally scoped to a folder).",
)
def list_notes(
    folder: Optional[str] = Field(
        default=None,
        description="Optional relative folder (trim '/' ; no '..' or '\\').",
    ),
) -> List[Dict[str, Any]]:
    start_time = time.time()
    user_id = _current_user_id()

    notes = vault_service.list_notes(user_id, folder=folder)

    duration_ms = (time.time() - start_time) * 1000
    logger.info(
        "MCP tool called",
        extra={
            "tool_name": "list_notes",
            "user_id": user_id,
            "folder": folder or "(root)",
            "result_count": len(notes),
            "duration_ms": f"{duration_ms:.2f}",
        },
    )

    return [
        {
            "path": entry["path"],
            "title": entry["title"],
            "last_modified": entry["last_modified"].isoformat(),
        }
        for entry in notes
    ]


@mcp.tool(name="read_note", description="Read a Markdown note with metadata and body.")
def read_note(
    path: str = Field(
        ..., description="Relative '.md' path ≤256 chars (no '..' or '\\')."
    ),
) -> dict:
    start_time = time.time()
    user_id = _current_user_id()

    note = vault_service.read_note(user_id, path)

    duration_ms = (time.time() - start_time) * 1000
    logger.info(
        "MCP tool called",
        extra={
            "tool_name": "read_note",
            "user_id": user_id,
            "note_path": path,
            "duration_ms": f"{duration_ms:.2f}",
        },
    )

    structured_note = {
        "title": note["title"],
        "note_path": note["path"],
        "body": note["body"],
        "metadata": note["metadata"],
        "updated": note["modified"].isoformat(),
    }

    return ToolResult(
        content=[TextContent(type="text", text=f"Read note: {note['title']}\n\n{note['body']}")],
        structured_content={"note": structured_note},
        meta={
            "openai/outputTemplate": "ui://widget/note.html",
            "openai/resultCanProduceWidget": True,
            "openai/toolInvocation/invoking": f"Opening {note['title']}...",
            "openai/toolInvocation/invoked": f"Loaded {note['title']}"
        }
    )


@mcp.tool(
    name="write_note",
    description="Create or update a note. Automatically updates frontmatter timestamps and search index.",
)
def write_note(
    path: str = Field(
        ..., description="Relative '.md' path ≤256 chars (no '..' or '\\')."
    ),
    body: str = Field(..., description="Markdown body ≤1 MiB."),
    title: Optional[str] = Field(
        default=None,
        description="Optional title override; otherwise frontmatter/H1/filename is used.",
    ),
    metadata: Optional[Dict[str, Any]] = Field(
        default=None,
        description="Optional frontmatter dict (tags arrays of strings; 'version' reserved).",
    ),
) -> dict:
    start_time = time.time()
    user_id = _current_user_id()

    note = vault_service.write_note(
        user_id,
        path,
        title=title,
        metadata=metadata,
        body=body,
    )
    indexer_service.index_note(user_id, note)

    duration_ms = (time.time() - start_time) * 1000
    logger.info(
        "MCP tool called",
        extra={
            "tool_name": "write_note",
            "user_id": user_id,
            "note_path": path,
            "duration_ms": f"{duration_ms:.2f}",
        },
    )

    structured_note = {
        "title": note["title"],
        "note_path": note["path"],
        "body": note["body"],
        "metadata": note["metadata"],
        "updated": note["modified"].isoformat(),
    }

    return ToolResult(
        content=[TextContent(type="text", text=f"Successfully saved note: {path}")],
        structured_content={"note": structured_note},
        meta={
            "openai/outputTemplate": "ui://widget/note.html",
            "openai/resultCanProduceWidget": True,
            "openai/toolInvocation/invoking": f"Saving {path}...",
            "openai/toolInvocation/invoked": f"Saved {path}"
        }
    )


@mcp.tool(name="delete_note", description="Delete a note and remove it from the index.")
def delete_note(
    path: str = Field(
        ..., description="Relative '.md' path ≤256 chars (no '..' or '\\')."
    ),
) -> Dict[str, str]:
    start_time = time.time()
    user_id = _current_user_id()

    vault_service.delete_note(user_id, path)
    indexer_service.delete_note_index(user_id, path)

    duration_ms = (time.time() - start_time) * 1000
    logger.info(
        "MCP tool called",
        extra={
            "tool_name": "delete_note",
            "user_id": user_id,
            "note_path": path,
            "duration_ms": f"{duration_ms:.2f}",
        },
    )

    return {"status": "ok"}


@mcp.tool(
    name="search_notes",
    description="Full-text search with snippets and recency-aware scoring.",
    meta={
        "openai/outputTemplate": "ui://widget/note.html",
        "openai/toolInvocation/invoking": "Searching...",
        "openai/toolInvocation/invoked": "Search complete."
    }
)
def search_notes(
    query: str = Field(..., description="Non-empty search query (bm25 + recency)."),
    limit: int = Field(50, ge=1, le=100, description="Result cap between 1 and 100."),
) -> ToolResult:
    start_time = time.time()
    user_id = _current_user_id()

    results = indexer_service.search_notes(user_id, query, limit=limit)

    duration_ms = (time.time() - start_time) * 1000
    logger.info(
        "MCP tool called",
        extra={
            "tool_name": "search_notes",
            "user_id": user_id,
            "query": query,
            "limit": limit,
            "result_count": len(results),
            "duration_ms": f"{duration_ms:.2f}",
        },
    )

    # Structure results for the widget
    structured_results = []
    for r in results:
        structured_results.append({
            "title": r["title"],
            "note_path": r["path"],
            "snippet": r["snippet"],
            "score": r["score"],
            "updated": r["updated"] if isinstance(r["updated"], str) else r["updated"].isoformat()
        })

    return ToolResult(
        content=[TextContent(type="text", text=f"Found {len(results)} notes matching '{query}'.")],
        structured_content={"results": structured_results},
        meta={
            "openai/outputTemplate": "ui://widget/note.html",
            "openai/resultCanProduceWidget": True,
            "openai/toolInvocation/invoking": f"Searching for '{query}'...",
            "openai/toolInvocation/invoked": f"Found {len(results)} results."
        }
    )



@mcp.tool(
    name="get_backlinks", description="List notes that reference the target note."
)
def get_backlinks(
    path: str = Field(
        ..., description="Relative '.md' path ≤256 chars (no '..' or '\\')."
    ),
) -> List[Dict[str, Any]]:
    user_id = _current_user_id()
    backlinks = indexer_service.get_backlinks(user_id, path)
    return backlinks


@mcp.tool(name="get_tags", description="List tags and associated note counts.")
def get_tags() -> List[Dict[str, Any]]:
    user_id = _current_user_id()
    return indexer_service.get_tags(user_id)


if __name__ == "__main__":
    transport = os.getenv("MCP_TRANSPORT", "stdio").strip().lower() or "stdio"

    # Configure HTTP transport with custom port if specified
    if transport == "http":
        port = int(os.getenv("MCP_PORT", "8001"))
        host = os.getenv("MCP_HOST", "127.0.0.1")
        logger.info(
            "Starting MCP server",
            extra={"transport": transport, "host": host, "port": port},
        )
        mcp.run(transport=transport, host=host, port=port)
    else:
        logger.info("Starting MCP server", extra={"transport": transport})
        mcp.run(transport=transport)