Proposal: REST API, OpenAPI spec and MCP server #471
Replies: 1 comment 1 reply
|
Nice sequencing — getting the OpenAPI spec right first, then deriving the MCP surface from it, is the order that avoids rework. One thing worth deciding early: once the OpenAPI spec exists, you don't necessarily need to hand-maintain a second MCP server. A gateway can consume the spec (or the REST endpoints directly) and emit MCP tools automatically — one endpoint, N tools, zero per-endpoint boilerplate. That's the shape we run (JiZhiMCP: host any HTTP API as MCP tools behind one streamable-HTTP endpoint): https://github.com/alanwang100/jizhineng-mcp The decision that matters most there is tool granularity: one MCP tool per REST endpoint, or grouped by resource (e.g. one |
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Status: Draft v1 (proposal) · Milestone: web2project v6.0 (see #484) · Baseline:
dev-5.0.0@179b4eaf(5.0.0-rc1)Related issues: #488 (Phase 0), #489 (Phase 1), #490 (Phase 2), #491 (Phase 3), #492 (Phase 4), #493 (Phase 5). Fixes that land before Phase 0: #472, #474, #476, #477, #479; fixed as part of Phase 0: #473, #475, #478. Open questions: #480, #481, #482, #483, #484, #485, #486, #487.
Related proposals: Pluggable File Backend (#404): file upload and download endpoints build on its Phase 1 storage facade, and webhook secrets use its secret store (#413). Identity Layer (#435): API credentials honor its user status and session epoch, and reuse its
SecretStoreandRateLimiter(#458). PSR-4 namespaces (#470): all new API code lives underWeb2project\insrc/.Prior art: caseysoftware/web2project-slim (2013), an experimental REST API on Slim that documented itself through HTTP OPTIONS.
1. Goals and non-goals
Goals
/api/v1/...) that is complete enough to replace the current UI. A new front end should need nothing else.load,store,delete,getAllowedRecords,can*). The API never has a permission path of its own.Non-goals for v1
2. Recommendation in brief
do_*_aed.phphandlers or reads$_POSTfrom inside model classes (section 3). An API built on today's models would either duplicate that logic or skip it. Move it into per-entity services that both the old UI handlers and the API call. This is the most important decision in the proposal.api/index.php) on Slim 4 (PSR-7/PSR-15). It runs without PHP sessions, HTML output or form nonces, and it shares the bootstrap, database and models withindex.php.CAppUIfor that user without a session, and set it as$GLOBALS['AppUI']. Every existingcan*()/phpGACL check then works unchanged. The context forces the user's time zone to UTC, so the existing user-time-to-UTC conversions inbind()do nothing and the API stays UTC end to end._AppUI,_perms,_query, password hashes and HTML-encoded strings.zircote/swagger-phpattributes on the controllers and schemas. The spec is generated in CI and committed, so diffs show up in review.api_eventstable. That one table feedsGET /changes?since=and webhook delivery.mcp/sdk.3. Current state: what helps and what blocks
Helps
w2p_Core_BaseObjectalready centralizes ACL.load()callscanView(),store()callscanEdit()/canCreate(),delete()callscanDelete(), and lists can usegetAllowedRecords()/getAllowedSQL()/setAllowedSQL().store(),delete()andload()publishpre*/post*events (w2p_System_Dispatcher), which gives a hook point for change capture.w2p_Controllers_Base::process()already has the bind, store or delete, and result shape that an API controller needs.MIN_PHP_VERSIONinbase.php), andpsr/containeris already installed.historyrecords most writes, andprojects,tasks,eventsandforumshave*_updatedcolumns.Blocks or complicates (file references are on
179b4eaf)modules/tasks/do_task_aed.php(171 lines: assignments, dependencies, dependency date shift, dynamics, budgets, departments, notify, project move); similar indo_project_aed,do_task_assign_aed,do_updatetask,do_file_aed,do_user_aed,projectdesigner/do_task_bulk_aedstore()would skip this logic. Move it into services (Phase 0).BaseObject::hook_postStore()binds custom fields from$_POST;CTask::store()reads$_POST['dosql']/hdependencies;CEventreads$_POST['event_assigned']/mail_invited$_POSTis empty, so any API save would zero the object's custom fields (#473) and skip the dependency checks.w2p_Extensions_Permissions::checkModule*()falls back to$GLOBALS['AppUI']->user_id;BaseObject::__constructcaptures the global$AppUIload()returnsfalsefor both; whenstore()is denied it records an empty database error (#478)BaseObject::bind()runshtmlentities()on every stringloadAll()has no ACL filterBaseObject::loadAll();CProjectoverrides it, most classes don't (#476)loadAll().BaseObjectcreates its ownw2p_System_Dispatcherand subscribes only itself (#475)CAppUI::login()reads$_POST['login']directlyprojects,tasks,eventsandforumshave*_updatedupdated_sincefilters need new columns or the outbox.store()CTask::updateSubTasksProject(), andCTask_Logupdates task fields with a direct query4. Architecture
Request lifecycle
api/index.phpincludesbase.php,includes/config.php,main_functions.phpanddb_adodb.php. It does not start a session, send HTML headers or load the theme.Authenticateresolves theAuthorization: Bearerheader to a token row, which gives a user and scopes. It rejects expired or revoked tokens, users who failcheckLogin, and (once identity Phase 0 lands) users whoseuser_statusis notactive.RequestContextbuilds the statelessCAppUIfor that user (section 5.3).application/problem+json.Code layout (PSR-4,
Web2project\→src/, as proposed in #470):5. Authentication and authorization
5.1 Personal access tokens (Phase 1)
w2p_pat_followed by 32 random bytes in base62. Only the SHA-256 hash and an 8-character prefix are stored, so the token is shown once. (Same storage pattern as the identity layer's SCIM tokens; the two token tables could share code.)modules/users), giving a name, scopes and an expiry (default 90 days, with a configurable maximum). Admins can list and revoke anyone's tokens.read,write,delete,admin, optionally per module (tasks:write). The effective right is the scope AND the phpGACL check.5.2 OAuth 2.1 (Phase 3)
league/oauth2-server9.x, a consent screen in the existing UI (normal login, any sign-in method) and an admin screen for clients (name, redirect URIs, allowed scopes). Works for every install. The identity proposal lists "web2project acting as an OAuth authorization server" as a non-goal for SSO; this would be a narrow server for API clients only.user_identities.aud(resource indicator) as well as signature, issuer and expiry.5.3 Request context
Add a stateless
CAppUIfactory (CAppUI::forUser(int $userId)). It loads the same user fieldslogin()loads, loads prefs, skips$_SESSION, sets theTIMEZONEpref to UTC for the API, and does not callregisterLogin(). Set$GLOBALS['AppUI']and$GLOBALS['acl']before any model is created (B3). The identity layer'sSessionEstablisher(#458) should share this loading code.phpGACL item permissions are cached and recalculated at login (
checkLogin()→recalcPermissions()). Token requests never log in, so either recalculate the token's user when its roles or permissions change, or recalculate once per token every few minutes (#481).5.4 Mapping ACL to HTTP
WWW-Authenticate: Bearerinsufficient_scopecanDelete()refused because of dependents (e.g. a project with tasks)isValid()/check()errors)If-MatchmismatchTo make this possible,
load(),store()anddelete()(or new*OrFail()variants used by the services) raise typed exceptions:NotFound,Forbidden,Validation,Conflict. The legacy methods keep their boolean returns.Lists are always built with
setAllowedSQL()/getAllowedRecords()(one query, not a check per item). Each item can include"_permissions": {"edit": true, "delete": false}on request (?include=permissions), which a UI needs to decide which buttons to show.6. Resources and URLs
Base:
/api/v1. Collections are plural nouns, sub-resources express ownership, and IDs are the existing integer keys.GET /me,GET/PATCH /me/preferences,GET /me/permissionsCUser,w2p_System_Preferences,w2p_Extensions_Permissions/companies,/companies/{id},/companies/{id}/departments,/projects,/contactsCCompany/departments,/departments/{id}CDepartmentparent_id/contacts,/contacts/{id},/contacts/{id}/methodsCContact/users,/users/{id}(directory fields); admin:POST/PATCH/DELETE,/users/{id}/roles,/users/{id}/tokensCUseruser_password/projects,/projects/{id}, sub:/tasks,/contacts,/departments,/budget,/files,/events,/forums,/historyCProject?status=&company_id=&owner_id=&updated_since=/tasks,/tasks/{id}, sub:/children,/assignments(PUT replaces),/dependencies(PUT replaces),/logs,/resources,/move(POST, between projects)CTask?project_id=&assignee=me&status=&due_before=/tasks/{id}/logs,/task-logs/{id}CTask_Log/events,/events/{id},/events/{id}/attendeesCEvent?from=&to=(calendar)/files,/files/{id},GET /files/{id}/content,POST /files(multipart),/file-foldersCFile,CFile_Folder/forums,/forums/{id}/messages,/messages/{id},PUT/DELETE /forums/{id}/watchCForum,CForum_Message/links,/links/{id}CLink/resources,/resources/{id}CResourceGET /history?table=&item=&project_id=CHistoryGET /changes?since=<cursor>&types=/sysvals/{key},/custom-fields?module=,/config/public,/locales/{lang},/modules(active modules only)w2PgetSysVal,w2p_Core_CustomFieldManager,w2p_System_Config,w2p_System_ModuleGET /search?q=&modules=hook_search/roles,/roles/{id}/permissions,/system/config,/system/modules,/sysvals(write),/billing-codes,/custom-fields(write)CSystem_Role,CSystem_SysVal,CSystem_Bcode,w2p_System_Moduleadminscope/projects/{id}/gantt,/reports/{name}w2p_Output_GanttRendererdata, reports moduleVerbs:
GETreads;POSTto a collection creates (201 with aLocationheader);PATCHupdates part of a record (JSON Merge Patch, RFC 7396);PUTonly for whole-collection replacement of a sub-resource (assignments, dependencies);DELETEdeletes (204). Actions that aren't CRUD are sub-resources withPOST(/tasks/{id}/move,/projects/{id}/duplicate,/tasks/{id}/notify).7. Conventions
{"data": {...}}. Collection:{"data": [...], "meta": {"total": n, "next": "<cursor or url>"}}.?include=for related objects, such asownerorcompany.name,start_date,owner_id) mapped by the transformers, so the API doesn't freeze the column prefixes (project_,task_). The cost is one mapping table per resource, which also serves as the field allow-list (API field names: clean names or raw column names? #480).2026-10-22T17:00:00Z). Pure dates areYYYY-MM-DD. The context's UTC time zone makes the existingbind()conversions inCTask/CEvent/CForumno-ops (section 5.3).bind()encodes on input (B5, Decode HTML entities in API output, or stop encoding on input first? #482). Input is accepted raw."custom_fields": {"<field_name>": value}. Only the fields that are sent are changed (Saving an object outside its edit form resets its custom fields to 0 #473).?limit=(default 50, maximum 200) with a cursor (next). Offset pagination (?page=) is allowed only on small lookup lists.?status=1&sort=-updated_at). Unknown parameters return 400 rather than being ignored silently.type,title,status,detail,errors[]). The_errorarrays from models are mapped to field errors.ETagon items, a weak tag from*_updatedor a row hash.PATCH/DELETEhonorIf-Match, so the UI and integrations don't overwrite each other's changes.Idempotency-Keyheader onPOST, stored for 24 hours (Phase 2).Deprecationheader.api/.*→api/index.php, withAuthorizationheader passthrough (CGIPassAuth On, or nginxfastcgi_param HTTP_AUTHORIZATION; the identity layer needs the same for SCIM). Responses sendCache-Control: private, no-storeunless anETagis set.8. Change detection: polling, feed and webhooks
updated_sinceon collections (Phase 1) for resources with*_updated. Phase 2 adds the column to the other core tables (section 12).OutboxListenersubscribes through a shared dispatcher (B7) topostCreateEvent/postUpdateEvent/postDeleteEvent. It writesapi_eventsrows (resource, id, action, actor, project_id, changed field names) in the same transaction as the change. Writes that bypassstore()(B10) record their event explicitly.GET /changes?since=<event_id>returns events the caller can currently view, filtered with the same allowed-SQL as lists. For deletes, it returns the event only if the caller could view the parent project. The cursor is the monotonicevent_id./webhooksCRUD, filtered by resource and event type), delivered by the cron and queue worker (queuescanner.php/w2p_System_EventQueue). The ACL is re-checked at delivery time as the subscription owner. Payloads are signed following the Standard Webhooks scheme (HMAC-SHA256,webhook-id/webhook-timestamp/webhook-signatureheaders), retried with exponential backoff, and disabled after repeated failures. The payload is thin ({type, id, occurred_at, url}); the receiver fetches the item, so no data leaks through stale permissions. The queue worker currently runs as user-1, so delivery must build a context for each owner.The
historytable is not suitable as the feed. It is written only when the history module is active, it is MyISAM,history_tableisvarchar(20), and it is ACL-filtered in PHP one row at a time (#477). It stays as the human-readable audit log.9. OpenAPI
zircote/swagger-php6.x attributes (#[OA\Get],#[OA\Schema]) on the controllers and the schema classes insrc/Api/Schema.composer openapiwritesapi/openapi.yaml(3.1); CI fails if the committed file differs from the generated one./api/docsserves Redoc or Swagger UI (static assets, bundled), and/api/v1/openapi.jsonserves the raw spec.bearerAuth(personal tokens) from Phase 1 andoauth2(authorizationCode with PKCE, plus scopes) from Phase 3.install/sql; and PHPUnit contract tests that check every response against its schema withopis/json-schema. (league/openapi-psr7-validatorsupports only OpenAPI 3.0.x.)openapi-generator(TypeScript for the new UI, Python for scripts). The SDKs are generated and not hand-maintained.10. MCP server (Phase 4)
mcp/sdk(maintained by the PHP Foundation and Symfony). v0.9.0 was released 2026-10-18 and is "experimental until 1.0". It supports stdio and Streamable HTTP and defines tools with#[McpTool]attributes that infer schemas from type hints. Pin~0.9and keep it behindsrc/Mcp.search,get_project_summary(status, % complete, critical and overdue tasks),list_my_tasks,get_task,create_task,update_task(progress, status, dates),log_time,list_recent_changes,post_forum_message. Each tool carries annotations (readOnlyHint,destructiveHint). Write tools need thewritescope. There is no delete tool in the first release.w2p://projects/{id},w2p://tasks/{id}. Prompts: "weekly status for project X", "what's overdue for me".bin/w2p-mcp --token=...or aW2P_TOKENenvironment variable) for local agents, using a personal token. This can ship right after Phase 1 as a read-only preview, because it needs only personal tokens and read services./mcp(Serve/mcpfrom the API app or a separate process? #486), using OAuth from Phase 3 under the MCP authorization spec (revision 2026-07-28): serve OAuth Protected Resource Metadata (RFC 9728) at/.well-known/oauth-protected-resource; return 401 withWWW-Authenticate: Bearer resource_metadata=...; accept only tokens whose audience is this server; return 403insufficient_scopenaming the needed scopes. Client registration via Client ID Metadata Documents is preferred over Dynamic Client Registration (How do MCP clients register: Client ID Metadata Documents or pre-registration? #485).11. Components to modify
Phase 0 (core groundwork, which also benefits the current UI)
classes/w2p/Core/BaseObject.class.phpsetCustomFields(array)rather than$_POSTinhook_postStore()(#473); typed exceptions or*OrFail()variants (B4); a permission error instead of an empty_error['store'](#478);listAllowed(filters, sort, limit, cursor)built onsetAllowedSQL()(B6)classes/w2p/Core/CustomFields.class.phpbind()changes only the keys present (today it sets missing ones to 0)classes/w2p/Core/CAppUI.class.phpforUser()factory (5.3), sharing code with the identity layer'sSessionEstablisherclasses/w2p/Extensions/Permissions.class.phpgetEffectivePermissions($userId)for/me/permissionsclasses/w2p/System/Dispatcher.class.php$eventoverwrite (#475); add a shared dispatcher for cross-cutting listeners (B7)modules/tasks/tasks.class.php$_POSTreads fromstore()(take dependencies as data); permission checks inmoveTaskBetweenProjects()(#472)modules/events/events.class.php$_POSTmodules/*/do_*_aed.php(tasks, projects, task assign, update task, files, users, projectdesigner bulk)$_POST→ call the service → redirectsrc/Service/*TaskServicefirst (largest), then Project, Contact, Company, Event, File, UserPhase 1+ (API)
api/index.php,api/.htaccess, nginx examplesrc/Api/*,src/Auth/Token/*modules/usersmodules/systeminstall/sql/0xx_*.sql+w2p_System_UpgradeManagerqueuescanner.php/w2p_System_EventQueuemodules/smartsearchhook_searchresults as structured data for/searchw2p_Output_GanttRenderer,modules/reports12. Data model changes
api_tokenstoken_id,user_id,name,prefixchar(8),token_hashchar(64) unique,scopes,created_at,expires_at,last_used_at,last_used_ip,revoked_at*_updatedoncompanies,contacts,departments,files,links,task_log,users,forum_messages,resourcesdatetime, set instore(); backfilled fromhistorywhere possibleapi_idempotencyapi_events(InnoDB)event_idbigint auto,occurred_at,resource,resource_id,action,actor_user_id,project_id,changed_fieldsJSONapi_webhooks,api_webhook_deliveriesSecretStore, #413/#458), filters, status, attemptsoauth_clients,oauth_auth_codes,oauth_access_tokens,oauth_refresh_tokens13. Libraries
slim/slimslim/psr7(ornyholm/psr7+nyholm/psr7-server)zircote/swagger-phpopis/json-schemamcp/sdkleague/oauth2-serverlcobucci/jwt,defuse/php-encryption,league/event,league/urifirebase/php-jwtguzzlehttp/guzzleleague/oauth2-clientmcp/sdkopenapi-generatorRate limiting reuses the identity layer's
RateLimiter(#458) rather than adding a package.Considered and not recommended
BaseObject+ ADOdb + phpGACL, and the ACL guarantee depends on going through it.?include=covers the use cases.14. Testing
15. Security
Authorization./api, so no CSRF surface. If the new UI later uses a cookie-based backend-for-frontend instead of OAuth, it needs its own CSRF protection (How does a replacement UI authenticate to the API? #483).user_password,user_*internals,_AppUI/_permsand private contact fields never serialize.(int)ids, known field names).adminscope can be granted only to users who already have system admin rights. Admin endpoints are audited inhistory.16. Phasing
All issues are in the web2project v6.0 milestone for now; #484 decides whether Phases 3–5 move to a later one. Sizes are relative (S < M < L < XL).
password-compatCAppUI::forUser(); shared dispatcher (#475);TaskService+ProjectServiceextracted, withdo_task_aed/do_project_aedcalling them$_POSTin*.class.phpapi/front controller, middleware, problem+json, pagination; personal tokens and the token UI; GET for me, companies, departments, contacts, users (directory), projects, tasks, task logs, events, files (metadata + download), forums, links, lookups;updated_sincewhere columns exist; OpenAPI + docs + CI gates. Optional: read-only stdio MCP preview*_updatedcolumns andapi_events; file upload (after #394)/changes; webhooks with signing and retries; OAuth 2.1 per #487/api/v1alone17. Open questions
bind()stops encoding and templates escape on output? The second is cleaner but is a large XSS-sensitive change to the UI. (Blocks Phase 1.)/mcpfrom the API app or a separate process? #486 Hosting/mcp: the same Slim app (simplest) or a separate long-running process (better for Streamable HTTP sessions under PHP-FPM)? (Blocks Phase 4.)league/oauth2-server, works everywhere), accept tokens from the organization's IdP configured in the identity layer, or both? (Blocks Phase 3.)18. Fixes found while writing this proposal
Found by reading the code on
dev-5.0.0@179b4eaf; not yet reproduced on a running install.==comparisonircmaxell/password-compatis no longer neededAll reactions