Skip to content
16 changes: 16 additions & 0 deletions .changeset/32686-upload-before-record.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
---
'@objectstack/service-storage': patch
'@objectstack/mcp': patch
'@objectstack/runtime': patch
---

feat(storage,mcp): an upload link for a file field of a record not yet created, so an agent can create a record whose file field is required

Clause-②: yes (widening)
Metadata-protocol: none

`create_upload_link` takes no `recordId` when it names a `field`: the link names the object and the file field only, and its answer carries `fileIds`, the id the upload is stored under. The user opens the link signed in and uploads; the agent then calls `create_record` with the field set to `fileIds[0]`. An expense line with a required e-invoice is created in two agent calls and one upload, and the field's `required` rule is unchanged.

Minting such a link asks the object's create permission for the user, and the field must be writable for them and not read-only; an attachments link still needs its record. The upload is checked against the field's `accept` and `maxSize` before the link is spent. The stored file is bound to the uploading user, the object and the field for one hour: until a record holds it, only that user's own write, into that field of that object, may use it, and within the hour no second record may take it while the first holds it. The uploader's write into another field or object, or after the hour, is refused at the field with the reason; another user's or a system write is refused as a file they cannot open. Once the hour has passed with a record holding it, or once a record lets it go, it is judged as any other record's file. Before the upload, the id takes no write but the uploader's, which is refused as an upload that never completed. Until a record has held the file, only its uploader may download it. The page the link opens says the file was received, and tells the user to go back to the assistant.

`fileIds` is an array so that a link for several files can answer several ids without a new key. Hosts whose storage service predates this keep `recordId` required on the tool, and the agent skill teaches the no-record form only where the host serves it.
20 changes: 20 additions & 0 deletions content/docs/ai/connect-mcp.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -316,6 +316,26 @@ record means no file**, refused with the same `RECORD_NOT_FOUND`.
`RECORD_LOCKED`). A field that becomes read-only after the link was made
refuses the upload when it arrives, attaching nothing. Sending a file's
bytes through the MCP protocol itself is not supported yet.
- **A record not created yet.** A record whose file field is `required` (an
expense line and its invoice, say) cannot be created before the file
exists, so `create_upload_link` also takes `objectName` and `field` with no
`recordId`. That needs a user who may create records of the object and
write the field, and a field that is not `readonly`; an attachments link
still needs its record. The answer carries `fileIds`, the id the upload is
stored under. Once the user has uploaded (the page says the file was
received), the agent calls `create_record` with the field set to
`fileIds[0]`, or the array for a multi-file field; before the upload that
create is refused as an upload that never completed. The field's own
`accept` and `maxSize` are checked when the file arrives, before the link is
spent. Until a record holds the file, the id works only for that user's own
`create_record` or `update_record` into that field of that object, within
one hour of the upload: the uploader's write into another field or object,
or after the hour, is refused at the field with the reason, and another
user's or a system write is refused as a file they cannot open. Within the
hour, a second record naming it while the first holds it is refused too.
After that it is the record's file like any other, and a file the record
lets go is judged as any released file. Until a record has held the file,
only the user who uploaded it can download it.

Reading a PDF or Word document's text runs on a pool of worker threads, so the
server keeps answering other requests while it does. Two host settings bound it, so
Expand Down
2 changes: 1 addition & 1 deletion content/docs/api/plugin-endpoints.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ other adapter.
| GET | `/storage/files/:fileId/url` | `storage.getDownloadUrl` | Resolve a short-lived signed download URL |
| GET | `/storage/files/:fileId` | — | Stable browser URL; 302s to the same signed URL (what file fields carry) |
| GET | `/storage/upload-links/:token` | — | The page a single-use upload link opens (minted by the MCP `create_upload_link` tool) for the signed-in user it was made for: a file picker |
| PUT | `/storage/upload-links/:token` | — | Spend the link on the request body, as that signed-in user; the file lands on the record and field the link is bound to |
| PUT | `/storage/upload-links/:token` | — | Spend the link on the request body, as that signed-in user; the file lands on the record and field the link is bound to, or, for a link that names no record, is stored for that field under the file id the link answered, for the user's create or update to name |

`storage.upload(file)` runs steps 1–3 for you, including the direct-to-storage
`PUT` in step 2. Step 1 refuses an empty `mimeType` with `400 INVALID_REQUEST`,
Expand Down
4 changes: 2 additions & 2 deletions content/docs/permissions/system-context.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -192,8 +192,8 @@ One of the largest consumers of the flag;
| 47b | The inbound-mail ingest seam: `ingest` admits the system context ALONE, and `rematch` admits it without the organization, owner or `manage_mailboxes` check | service-mailbox | Get: a mail source hands a mailbox its messages, and server code re-matches any mailbox. Lose: nothing a user held — every other caller of `ingest` is refused (`PERMISSION_DENIED`), because an ingested message is shown on every record its correspondents' addresses match and a user who could hand the seam a message could write one in a correspondent's name; every other caller of `rematch` must be in the mailbox's organization and own the mailbox or hold `manage_mailboxes` | `ingest`, `authorizeRematch` |
| 47c | The inbound-mail IMAP sync: `syncMailbox` and `syncAll` admit the system context ALONE | service-mailbox | Get: the sync job reads every mailbox row (its organization, address and IMAP cursor), writes the cursor back, and hands each fetched message to `ingest` under the system context. Lose: nothing a user held — every other caller is refused (`PERMISSION_DENIED`), because a sync stores a mailbox's mail and moves its cursor | `syncMailbox`, `syncAll` |
| 47d | The print service REFUSES the system context: `printRecordToFile` admits a human user acting for themselves alone | service-print | Get: nothing — a system caller is refused (`PERMISSION_DENIED`) before any page is read, session minted or browser started. Lose: nothing a user held — the PDF is rendered as the requesting user and never as the system, so a record is archived only by someone who could read it | `refuseUnlessHumanCaller` |
| 47e | The caller-scoped attach verbs REFUSE the system context: `attachFileAs` and `assertMayAttach` admit a signed-in user alone, and so do the caller-scoped record-file verbs the MCP `read_file` and `create_upload_link` tools call (`listRecordFilesAs`, `readRecordFileAs`, `createUploadLinkAs`) | service-storage | Get: nothing — a system caller is refused (`PERMISSION_DENIED`); the system attaches through `attachFile`, whose rows name no user. Lose: nothing a user held — the caller-scoped verbs insert the attachment under the caller's context so every insert gate judges that user and both rows name them, and the record-file verbs read the record and judge the file as that user, and bind an upload link to them | `packages/services/service-storage/src/file-attachment-service.ts#requireUserContext`, `packages/services/service-storage/src/record-file-access.ts#requireUserContext` |
| 47f | The file-reference claim path asks no read verdict of a system write: a record write claims or copies a referenced file only as its caller may read it (the download door's verdict), and a system write carries no caller to ask | service-storage | Get: a system write claims or copies any file the organization-scoped lookup reaches, as before #25692; a deliberate server-side copy between records runs this way. Lose: nothing a user held — a user write is judged by the download door's verdict, and a context-less programmatic write is not asked either | `referencingCallerOf` |
| 47e | The caller-scoped attach verbs REFUSE the system context: `attachFileAs` and `assertMayAttach` admit a signed-in user alone, and so do the caller-scoped record-file verbs the MCP `read_file` and `create_upload_link` tools call (`listRecordFilesAs`, `readRecordFileAs`, `createUploadLinkAs`, `createUploadLinkForNewRecordAs`) | service-storage | Get: nothing — a system caller is refused (`PERMISSION_DENIED`); the system attaches through `attachFile`, whose rows name no user. Lose: nothing a user held — the caller-scoped verbs insert the attachment under the caller's context so every insert gate judges that user and both rows name them, and the record-file verbs read the record and judge the file as that user, and bind an upload link to them; `createUploadLinkForNewRecordAs` names no record, so it asks the object's create verdict and the field's writability as that user instead | `packages/services/service-storage/src/file-attachment-service.ts#requireUserContext`, `packages/services/service-storage/src/record-file-access.ts#requireUserContext` |
| 47f | The file-reference claim path asks no read verdict of a system write: a record write claims or copies a referenced file only as its caller may read it (the download door's verdict), and a system write carries no caller to ask | service-storage | Get: a system write claims or copies any file the organization-scoped lookup reaches, as before #25692; a deliberate server-side copy between records runs this way. The exception is a file uploaded through an upload link that names no record (#32686), and the id such a link answers before its upload: until a record has held the file, only its uploader's own write takes it, so a system write naming it is refused at the field. Once a record holds it, a system write copies it as any; once a record lets it go, it is judged as any released file. Lose: nothing a user held — a user write is judged by the download door's verdict, and a context-less programmatic write is not asked either | `referencingCallerOf` |
| 47g | The `sys_file` storage-owned columns guard returns early on create: a system insert keeps the `key`, `mime_type`, `size`, `status` and `etag` it writes | service-storage | Get: the storage service's own inserts (the upload doors, the field-file copy and backfill) write those five columns. Lose: nothing a user held — a non-system create has them dropped and starts `pending`, and on update the same columns are `readonly`, so the UPDATE `readonly` strip keeps them for every non-system caller | `installSysFileStorageOwnedColumnsGuard` |

### 5. Actions, metadata plane, provenance, the organization wall
Expand Down
16 changes: 16 additions & 0 deletions packages/mcp/src/file-content.ts
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,16 @@ export interface McpUploadLink {
expiresAt: string;
}

/**
* [#32686] A single-use upload link for a file field of a record not yet
* created, with the file id(s) the upload is stored under: the value the
* agent writes into the field when it creates the record. An array so that a
* link taking several files answers more entries, not a second key.
*/
export interface McpNewRecordUploadLink extends McpUploadLink {
fileIds: string[];
}

/**
* [#30892] The file seam of the HTTP MCP tools, implemented by the runtime
* over the storage plugin's `file-attachments` service. Every member runs AS
Expand All @@ -331,6 +341,12 @@ export interface McpFileBridge {
): Promise<McpReadFile>;
/** A single-use upload link bound to exactly this record and field (or its attachments). */
createUploadLink?(object: string, recordId: string, target: McpUploadLinkTarget): Promise<McpUploadLink>;
/**
* [#32686] A single-use upload link for a file field of a record the caller
* is about to create. Optional on its own: a host without it serves links
* for existing records only, and `create_upload_link` then needs `recordId`.
*/
createUploadLinkForNewRecord?(object: string, target: { field: string }): Promise<McpNewRecordUploadLink>;
}

/** One MCP tool-result content block `read_file` answers with. */
Expand Down
98 changes: 98 additions & 0 deletions packages/mcp/src/mcp-file-tools.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -472,6 +472,104 @@ describe('create_upload_link', () => {
});
});

/** [#32686] A bridge that also serves a link for a record not yet created. */
function newRecordBridge() {
const bridge = fullBridge();
Object.assign(bridge, {
async createUploadLinkForNewRecord(object: string, target: { field: string }) {
bridge.calls.push(['createUploadLinkForNewRecord', object, target]);
if (object === 'locked') {
throw Object.assign(new Error('You cannot upload a file for a new locked: you cannot create locked records.'), {
code: 'PERMISSION_DENIED',
status: 403,
});
}
return {
url: 'https://acme.test/api/v1/storage/upload-links/f9.sec',
expiresAt: '2026-11-13T12:10:00.000Z',
fileIds: ['f9'],
};
},
} satisfies McpFileBridge);
return bridge;
}

async function uploadLinkSchema(runtime: MCPServerRuntime, bridge: unknown) {
const json = await rpc(runtime, bridge, undefined, { jsonrpc: '2.0', id: 1, method: 'tools/list' });
const tool = (json.result?.tools ?? []).find((t: { name: string }) => t.name === 'create_upload_link');
return tool as { description: string; inputSchema: { required?: string[]; properties: Record<string, unknown> } };
}

describe('[#32686] create_upload_link for a record not yet created', () => {
let runtime: MCPServerRuntime;
beforeEach(() => {
runtime = new MCPServerRuntime({ name: 'file-tools', version: '0.0.0' });
});

it('with no recordId and a field, mints through the bridge and answers the file id the create names', async () => {
const bridge = newRecordBridge();
const result = await callTool(runtime, bridge, 'create_upload_link', { objectName: 'expense_line', field: 'invoice' });
expect(result.isError).toBeFalsy();
expect(bridge.calls).toEqual([['createUploadLinkForNewRecord', 'expense_line', { field: 'invoice' }]]);
const facts = factsOf(result);
expect(facts).toMatchObject({
url: 'https://acme.test/api/v1/storage/upload-links/f9.sec',
expiresAt: '2026-11-13T12:10:00.000Z',
singleUse: true,
objectName: 'expense_line',
field: 'invoice',
fileIds: ['f9'],
});
expect(facts).not.toHaveProperty('recordId');
expect(facts.instructions).toContain('fileIds[0]');
});

it('with a recordId, still asks for that record\'s link, never the new-record one', async () => {
const bridge = newRecordBridge();
await callTool(runtime, bridge, 'create_upload_link', { objectName: 'claim', recordId: 'c1', field: 'policy' });
expect(bridge.calls).toEqual([['createUploadLink', 'claim', 'c1', { field: 'policy' }]]);
});

it('refuses an attachments link with no record before asking the bridge', async () => {
const bridge = newRecordBridge();
const result = await callTool(runtime, bridge, 'create_upload_link', { objectName: 'claim', attachments: true });
expect(result.isError).toBe(true);
expect(textOf(result.content[0])).toContain('An attachment needs its record');
expect(bridge.calls).toEqual([]);
});

it('relays the minting refusal with its code', async () => {
const result = await callTool(runtime, newRecordBridge(), 'create_upload_link', { objectName: 'locked', field: 'invoice' });
expect(result.isError).toBe(true);
expect(JSON.parse(textOf(result.content[0])).error).toMatchObject({ code: 'PERMISSION_DENIED', status: 403 });
});

it('lists recordId as optional, and says how, only where the bridge serves it', async () => {
const served = await uploadLinkSchema(runtime, newRecordBridge());
expect(served.inputSchema.required ?? []).not.toContain('recordId');
expect(served.description).toContain('omit recordId and name the field');
const notServed = await uploadLinkSchema(runtime, fullBridge());
expect(notServed.inputSchema.required).toContain('recordId');
expect(notServed.description).not.toContain('omit recordId');
});

it('a bridge without it refuses a call with no recordId, asking nothing', async () => {
const bridge = fullBridge();
const result = await callTool(runtime, bridge, 'create_upload_link', { objectName: 'expense_line', field: 'invoice' });
expect(result.isError).toBe(true);
expect(bridge.calls).toEqual([]);
});

it('the skill teaches the two-call flow only where the host says the bridge serves it, and only with data:write', () => {
const marker = 'omit `recordId` and name `field`';
expect(renderSkillMarkdown({ fileTools: true, newRecordUploadLinks: true })).toContain(marker);
expect(renderSkillMarkdown({ fileTools: true })).not.toContain(marker);
expect(renderSkillMarkdown({ fileTools: true, newRecordUploadLinks: true, grantedScopes: [MCP_OAUTH_SCOPE_DATA_READ] })).not.toContain(marker);
expect(renderSkillMarkdown({ fileTools: true, newRecordUploadLinks: true, grantedScopes: [MCP_OAUTH_SCOPE_DATA_WRITE] })).toContain(marker);
expect(renderSkillMarkdown({ newRecordUploadLinks: true })).not.toContain(marker);
});
});

describe('the skill teaches the file tools exactly where they register', () => {
it('names both for a host that carries them, and each only for the scope that registers it', () => {
const all = renderSkillMarkdown({ fileTools: true });
Expand Down
Loading
Loading