The notes existed but there was nowhere to write them: a CLI command on a laptop, a tool call through Claude, or a file in a Docker volume. None of those is reachable from a phone in a lesson, which is where notes are actually taken. So: `/app`, served only when WEB_PASSWORD is set. A login, the day's notes, and a settings page for the Schulcloud token — the one surface here meant for a person rather than a program. The shape follows how the notes are written: one note per school day, one `##` heading per lesson, prose and lists and tables beneath. That turns out to be the design decision that matters, twice over. First, it is what lets WebUntis earn its keep. Opening a day with no note fills in that day's lessons — numbered, with times, teacher and room, cancellations dropped and substitutions marked. Retyping the timetable is exactly the work the second upstream exists to avoid, and "Stunden ergänzen" tops up a note started before the day ended without touching what is already written. Second, it changes how notes are indexed. A day note is indexed per lesson, not whole: search answers "my own note, Deutsch, 18.09.2026" rather than "my own note, Friday", and `list_notes subject=Deutsch` finds a day whose frontmatter names no subject at all. Indexed whole, every hit would read as a weekday and "what did we do in Deutsch" would match notes whose other five lessons were something else. `lessonHeading` and `subjectFromHeading` are a loop — the app writes the heading, the indexer reads the subject back out — and a test holds them to it. Notes taken in a lesson cannot be retaken, so the editor is built around not losing them: autosave, every keystroke mirrored to local storage, a save when the phone locks, and a fallback to the local copy when the request never arrives. A save that would overwrite a version the editor never saw is refused and the choice handed back — the notes folder is synced and open in more than one place, and a phone must not silently win over a laptop. `replaceNote` is separate from `writeNote` for that reason: never-overwrite is right for `add_note` and exactly wrong for an editor. WEB_PASSWORD is the first credential here a human types, so it is the first that can be guessed: scrypt at startup, never stored or compared in the clear, per-address rate limiting — which is not decoration, since the scrypt cost is itself a denial-of-service vector without it. The session is a signed HttpOnly SameSite=Strict cookie whose key is derived from the password, so changing it logs everyone out and there is no second secret to keep. It opens /api, because a session is the user, and never /mcp, because nothing in a browser speaks MCP. Also here, because the app made them matter: frontmatter now reads the indented `- item` list form editors write, so an Obsidian vault round-trips its tags; and a four-digit folder is a filing scheme, not a subject, so `2026/` does not file a school year under one. 357 tests; 106/107 smoke against the local instance, the one failure being the H5P service that instance does not run. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
185 lines
6.8 KiB
TypeScript
185 lines
6.8 KiB
TypeScript
import crypto from 'node:crypto';
|
|
import express, { type Request, type Response } from 'express';
|
|
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
|
|
import { isInitializeRequest } from '@modelcontextprotocol/sdk/types.js';
|
|
import type { Config } from '../config.ts';
|
|
import { createServer } from '../mcp/server.ts';
|
|
import type { Services } from '../services.ts';
|
|
import { createApiRouter } from './api.ts';
|
|
import { createAppRouter } from './app-page.ts';
|
|
import { bearerAuth, pathSecret } from './auth.ts';
|
|
import { tokenPage, tokenScript } from './token-page.ts';
|
|
|
|
/**
|
|
* Streamable-HTTP front end, for use as a remote MCP connector.
|
|
*
|
|
* Sessions are stateful: a client POSTs `initialize`, gets an
|
|
* `Mcp-Session-Id` back, and reuses it for subsequent POSTs, an optional GET
|
|
* (the SSE channel for server-initiated messages), and a DELETE to close.
|
|
* Each session owns one McpServer instance, which keeps per-session caches
|
|
* (the `/me` lookup) from leaking between callers.
|
|
*/
|
|
|
|
const MCP_PATH = '/mcp';
|
|
/** The CLI's surface: file bytes, sync manifest, on-demand re-crawl. */
|
|
const API_PATH = '/api';
|
|
/** Sessions are dropped after this long without traffic, in case DELETE never arrives. */
|
|
const SESSION_IDLE_MS = 30 * 60 * 1000;
|
|
|
|
interface Session {
|
|
transport: StreamableHTTPServerTransport;
|
|
close: () => Promise<void>;
|
|
lastSeen: number;
|
|
}
|
|
|
|
export function createHttpApp(config: Config, services?: Services): express.Express {
|
|
const app = express();
|
|
app.disable('x-powered-by');
|
|
// Caddy sits in front and terminates TLS; trust its forwarding headers so
|
|
// logged client IPs are real rather than the proxy's.
|
|
app.set('trust proxy', true);
|
|
|
|
const sessions = new Map<string, Session>();
|
|
|
|
const sweep = setInterval(() => {
|
|
const cutoff = Date.now() - SESSION_IDLE_MS;
|
|
for (const [id, session] of sessions) {
|
|
if (session.lastSeen < cutoff) {
|
|
sessions.delete(id);
|
|
void session.close().catch(() => {});
|
|
}
|
|
}
|
|
}, 60_000);
|
|
sweep.unref();
|
|
|
|
// Liveness probe for Docker/Caddy. Deliberately before auth and free of any
|
|
// detail about the instance or the account.
|
|
app.get('/healthz', (_req, res) => {
|
|
res.json({ status: 'ok', sessions: sessions.size, index: services?.store ? 'on' : 'off' });
|
|
});
|
|
|
|
// MCP_AUTH_TOKEN opens both surfaces: the MCP endpoint and the CLI's API. The
|
|
// connector token opens /mcp alone. claude.ai stores it as a request header,
|
|
// and a credential held by a third party should reach the read-only tools,
|
|
// not /api, which can replace the Schulcloud token and stream the file mirror.
|
|
// The web app, when a password is configured. Mounted before the token gate
|
|
// so its login screen is reachable without one — it is the thing that issues
|
|
// the session everything else then accepts.
|
|
const appSurface = services ? createAppRouter(config) : undefined;
|
|
if (appSurface) app.use('/app', appSurface.router);
|
|
|
|
const loggedIn = appSurface ? (req: Request) => appSurface.auth.verify(req.get('cookie')) : undefined;
|
|
|
|
if (config.authToken) {
|
|
app.use(MCP_PATH, bearerAuth(config.connectorToken ? [config.authToken, config.connectorToken] : config.authToken));
|
|
app.use(API_PATH, bearerAuth(config.authToken, loggedIn));
|
|
} else {
|
|
console.warn(
|
|
'[schulcloud-mcp] MCP_AUTH_TOKEN is not set — the endpoint is UNAUTHENTICATED. ' +
|
|
'Only acceptable when bound to localhost or an otherwise private network.',
|
|
);
|
|
}
|
|
|
|
if (services) {
|
|
app.use(API_PATH, createApiRouter(services));
|
|
// The page to paste a fresh Schulcloud token into. It holds no secret: what
|
|
// it sends goes to /api/token, behind the bearer check above.
|
|
app.get('/token', tokenPage);
|
|
app.get('/token.js', tokenScript);
|
|
}
|
|
|
|
const handlePost = async (req: Request, res: Response): Promise<void> => {
|
|
const sessionId = req.get('mcp-session-id');
|
|
|
|
try {
|
|
if (sessionId) {
|
|
const session = sessions.get(sessionId);
|
|
if (!session) {
|
|
res.status(404).json(rpcError(-32001, 'Unknown or expired session. Re-initialize.'));
|
|
return;
|
|
}
|
|
session.lastSeen = Date.now();
|
|
await session.transport.handleRequest(req, res, req.body);
|
|
return;
|
|
}
|
|
|
|
if (!isInitializeRequest(req.body)) {
|
|
res.status(400).json(rpcError(-32000, 'Missing Mcp-Session-Id header; send an initialize request first.'));
|
|
return;
|
|
}
|
|
|
|
const { server } = createServer(config, services);
|
|
const transport = new StreamableHTTPServerTransport({
|
|
sessionIdGenerator: () => crypto.randomUUID(),
|
|
onsessioninitialized: (id) => {
|
|
sessions.set(id, {
|
|
transport,
|
|
close: async () => {
|
|
await transport.close().catch(() => {});
|
|
await server.close().catch(() => {});
|
|
},
|
|
lastSeen: Date.now(),
|
|
});
|
|
console.log(`[schulcloud-mcp] session ${id} initialized`);
|
|
},
|
|
});
|
|
|
|
transport.onclose = () => {
|
|
if (transport.sessionId) {
|
|
sessions.delete(transport.sessionId);
|
|
console.log(`[schulcloud-mcp] session ${transport.sessionId} closed`);
|
|
}
|
|
};
|
|
|
|
await server.connect(transport);
|
|
await transport.handleRequest(req, res, req.body);
|
|
} catch (error) {
|
|
console.error('[schulcloud-mcp] POST failed:', error);
|
|
if (!res.headersSent) res.status(500).json(rpcError(-32603, 'Internal server error'));
|
|
}
|
|
};
|
|
|
|
app.post(MCP_PATH, express.json({ limit: '4mb' }), handlePost);
|
|
|
|
// GET opens the server→client SSE stream; DELETE ends the session.
|
|
const bySession = async (req: Request, res: Response): Promise<void> => {
|
|
const sessionId = req.get('mcp-session-id');
|
|
const session = sessionId ? sessions.get(sessionId) : undefined;
|
|
if (!session) {
|
|
res.status(404).json(rpcError(-32001, 'Unknown or expired session.'));
|
|
return;
|
|
}
|
|
session.lastSeen = Date.now();
|
|
try {
|
|
await session.transport.handleRequest(req, res);
|
|
} catch (error) {
|
|
console.error('[schulcloud-mcp] session request failed:', error);
|
|
if (!res.headersSent) res.status(500).json(rpcError(-32603, 'Internal server error'));
|
|
}
|
|
};
|
|
|
|
app.get(MCP_PATH, bySession);
|
|
app.delete(MCP_PATH, bySession);
|
|
|
|
// The same endpoint without a bearer token, for clients that cannot send one:
|
|
// claude.ai's connector dialog takes only a URL. The path is the credential
|
|
// here, so nothing in this server logs request paths — keep it that way — and
|
|
// the Caddy snippet redacts it from the access log. A stopgap until the
|
|
// endpoint speaks OAuth, which is what connectors are meant to use.
|
|
if (config.mcpPathSecret) {
|
|
const secretMcpPath = '/:secret/mcp';
|
|
const gate = pathSecret(config.mcpPathSecret);
|
|
app.post(secretMcpPath, gate, express.json({ limit: '4mb' }), handlePost);
|
|
app.get(secretMcpPath, gate, bySession);
|
|
app.delete(secretMcpPath, gate, bySession);
|
|
}
|
|
|
|
app.use((_req, res) => res.status(404).json({ error: 'not_found' }));
|
|
|
|
return app;
|
|
}
|
|
|
|
function rpcError(code: number, message: string) {
|
|
return { jsonrpc: '2.0' as const, error: { code, message }, id: null };
|
|
}
|