@punica/form-mcp 0.2.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -10,12 +10,12 @@ and validates its answer.
10
10
 
11
11
  ## Tools
12
12
 
13
- | Tool | What it does |
14
- | --- | --- |
15
- | `get_guide` | The rules: what the packages provide and what your application builds, the lifecycle, services, events and a complete example |
16
- | `search_api` | Finds exports of `@punica/form` and `@punica/form-service` by name or documentation |
17
- | `get_api` | The exact TypeScript declaration and documentation of one or more exports |
18
- | `validate_code` | Checks code for imports that do not exist, wrong service names and service calls that do not exist; each problem with a fix |
13
+ | Tool | What it does |
14
+ | --------------- | ----------------------------------------------------------------------------------------------------------------------------- |
15
+ | `get_guide` | The rules: what the packages provide and what your application builds, the lifecycle, services, events and a complete example |
16
+ | `search_api` | Finds exports of `@punica/form` and `@punica/form-service` by name or documentation |
17
+ | `get_api` | The exact TypeScript declaration and documentation of one or more exports |
18
+ | `validate_code` | Checks code for imports that do not exist, wrong service names and service calls that do not exist; each problem with a fix |
19
19
 
20
20
  Resources: `punica-form://guide` and `punica-form://api/<name>`.
21
21
 
@@ -34,8 +34,8 @@ export declare class FormController<E extends object, F extends FormItem<E> = Fo
34
34
  */
35
35
  static fromEntity<E extends object, F extends FormItem<E> = FormItem<E>>(entity: E, options?: FormControllerOptions): Promise<FormController<E, F>>;
36
36
  /**
37
- * The current form. It is never changed: after a change this returns a
38
- * new object.
37
+ * The current form. A form object is never changed once it is returned:
38
+ * after `start()` and after every change this returns a new object.
39
39
  */
40
40
  getForm: () => Form<E, F>;
41
41
  /**
@@ -49,10 +49,15 @@ export declare class FormController<E extends object, F extends FormItem<E> = Fo
49
49
  */
50
50
  on<K extends keyof FormEventMap<E, F>>(event: K, handler: (payload: FormEventMap<E, F>[K]) => void): () => void;
51
51
  /**
52
- * The service of a class listed in `@Services`.
53
- * @throws When the form has no service of the class
52
+ * The service of a class listed in `@Services`, or of a subclass of it.
53
+ * @throws When the form is not started yet or has no service of the class
54
54
  */
55
55
  getService<S extends IService>(service: ServiceClass<S>): BoundService<S, E, F>;
56
+ /**
57
+ * Runs changes as one: subscribers and UPDATE_FORM listeners are notified
58
+ * once, after the function returned or the promise it returned settled.
59
+ */
60
+ batch: <T>(change: () => T) => T;
56
61
  /**
57
62
  * Starts the form: runs its readers and starters and initializes its
58
63
  * services.
@@ -6,4 +6,4 @@ export declare const DECORATOR_READERS = "form-readers";
6
6
  /**
7
7
  * Decorator for adding readers to a form class.
8
8
  */
9
- export declare const Readers: <E, F extends FormItem<E>>(data: IReader<E, F>[]) => FormClassDecorator;
9
+ export declare const Readers: <E, F extends FormItem<E>>(data: Array<IReader<E, F>>) => FormClassDecorator;
@@ -6,4 +6,4 @@ export declare const DECORATOR_SERVICES = "form-services";
6
6
  /**
7
7
  * Decorator for adding services to a form class.
8
8
  */
9
- export declare const Services: (data: Array<IService>) => FormClassDecorator;
9
+ export declare const Services: (data: Array<IService | (new () => IService)>) => FormClassDecorator;
@@ -6,4 +6,4 @@ export declare const DECORATOR_STARTERS = "form-starters";
6
6
  /**
7
7
  * Decorator for adding starters to a form class.
8
8
  */
9
- export declare const Starters: <E, F extends FormItem<E>>(data: IStarter<E, F>[]) => FormClassDecorator;
9
+ export declare const Starters: <E, F extends FormItem<E>>(data: Array<IStarter<E, F>>) => FormClassDecorator;
@@ -11,5 +11,5 @@ export declare const FORM_ITEMS = "form-items";
11
11
  */
12
12
  declare const defineFormItem: <T extends object>(type: string, renderer: Renderer, options?: {
13
13
  register?: FormItemRegister;
14
- }) => (data: T) => FormPropertyDecorator;
14
+ }) => ((data: T) => FormPropertyDecorator);
15
15
  export default defineFormItem;
@@ -4,5 +4,5 @@ import { FormPropertyDecorator } from './decorator';
4
4
  * class. Read it back in a reader with `getFormItemProperties(entity, key)`.
5
5
  * @param key - Identifies the data
6
6
  */
7
- declare const defineFormItemProperty: <T>(key: string) => (data: T) => FormPropertyDecorator;
7
+ declare const defineFormItemProperty: <T>(key: string) => ((data: T) => FormPropertyDecorator);
8
8
  export default defineFormItemProperty;
@@ -4,5 +4,5 @@ import { FormClassDecorator } from './decorator';
4
4
  * in a reader with `getFormProperty(entity, key)`.
5
5
  * @param key - Identifies the data
6
6
  */
7
- declare const defineFormProperty: <T>(key: string) => (data: T) => FormClassDecorator;
7
+ declare const defineFormProperty: <T>(key: string) => ((data: T) => FormClassDecorator);
8
8
  export default defineFormProperty;
@@ -3,7 +3,7 @@
3
3
  * the legacy one (`experimentalDecorators`) and the standard one.
4
4
  */
5
5
  /** A class decorator. Both implementations pass the class first. */
6
- export type FormClassDecorator = (target: Function, context?: ClassDecoratorContext) => void;
6
+ export type FormClassDecorator = (target: object, context?: ClassDecoratorContext) => void;
7
7
  /**
8
8
  * A property decorator: `(prototype, propertyKey)` for the legacy
9
9
  * implementation, `(undefined, context)` for the standard one.
@@ -1,7 +1,3 @@
1
- /**
2
- * The metadata decorators attach to form classes. It is kept per class, so
3
- * no reflection polyfill is needed.
4
- */
5
1
  export declare const setFormProperty: (target: object, key: string, data: unknown) => void;
6
2
  export declare const setFormItemProperty: (target: object, key: string, property: string, data: unknown) => void;
7
3
  /**
@@ -17,6 +17,12 @@ export type CommandService<E, F extends FormItem<E>> = {
17
17
  * reference and UPDATE_FORM is fired. Unknown properties are ignored.
18
18
  */
19
19
  setItems: (items: Array<FormItem<E>>) => void;
20
+ /**
21
+ * Marks the pending asynchronous writes of a property, or of the whole
22
+ * form when no property is given, as superseded by a newer one.
23
+ * @returns A function that tells whether this write is still the newest
24
+ */
25
+ supersede: (property?: keyof E) => () => boolean;
20
26
  /** Fires an event of the controller. */
21
27
  emit: <K extends keyof FormEventMap<E, F>>(event: K, payload: FormEventMap<E, F>[K]) => void;
22
28
  /** Creates what the functions of a form item receive. */
@@ -5,7 +5,8 @@ import { FormItem, IReader, IService, IStarter } from '../..';
5
5
  */
6
6
  export type Form<E, F extends FormItem<E> = FormItem<E>> = {
7
7
  items: F[];
8
- services?: IService[];
8
+ /** Service classes (one instance per form) or instances. */
9
+ services?: Array<IService | (new () => IService)>;
9
10
  readers?: Array<IReader<E, F>>;
10
11
  starters?: Array<IStarter<E, F>>;
11
12
  [key: string]: unknown;
@@ -25,12 +25,26 @@ export type FormItem<E> = {
25
25
  /** The messages of the last failed validation. */
26
26
  errorMessages?: string[];
27
27
  /** Runs once while the form is created; the returned items are written to the form. */
28
- initialize?: (command: CommandItem<E, FormItem<E>>) => Promise<Array<FormItem<E>>>;
28
+ initialize?(command: CommandItem<E, FormItem<E>>): Promise<Array<FormItem<E>>>;
29
29
  /** Runs after the value of the item was set; the returned items are written to the form. */
30
- control?: (command: CommandItem<E, FormItem<E>>) => Promise<Array<FormItem<E>>>;
30
+ control?(command: CommandItem<E, FormItem<E>>): Promise<Array<FormItem<E>>>;
31
31
  /** Validates the item. */
32
- validation?: (command: CommandItem<E, FormItem<E>>) => Promise<ErrorDetail>;
32
+ validation?(command: CommandItem<E, FormItem<E>>): Promise<ErrorDetail>;
33
33
  };
34
+ /**
35
+ * A form item whose `value` has the type of its property. Use it as the item
36
+ * type of a form to get checked values after narrowing by `property`:
37
+ *
38
+ * const controller = await FormController.fromEntity<User, TypedFormItem<User>>(user);
39
+ * const item = controller.getForm().items[0];
40
+ * if (item.property === 'age') item.value; // number | undefined
41
+ */
42
+ export type TypedFormItem<E, F extends FormItem<E> = FormItem<E>> = {
43
+ [K in keyof E]: Omit<F, 'property' | 'value'> & {
44
+ property: K;
45
+ value?: E[K];
46
+ };
47
+ }[keyof E];
34
48
  /**
35
49
  * The result of a validation.
36
50
  */
@@ -1 +1 @@
1
- {"version":"2.0.0"}
1
+ {"version":"2.1.0"}
@@ -3,8 +3,9 @@ import { FormItem, IReader } from '..';
3
3
  * Creates the reader that turns an entity into a form:
4
4
  *
5
5
  * 1. the services, readers and starters of the class decorators
6
- * 2. one item for every decorated property the entity holds, in the order
7
- * of the properties
6
+ * 2. one item for every decorated property, in the order of the properties
7
+ * of the entity; decorated properties the entity does not hold (declared
8
+ * without a value) follow
8
9
  * 3. the values of the entity
9
10
  * 4. the `initialize` function of every item that has one
10
11
  */
@@ -0,0 +1,20 @@
1
+ import type { FormItemRegister } from './register';
2
+ /**
3
+ * The state every copy of this package shares. A project can load the ESM
4
+ * and the CommonJS build side by side (an app and its test runner, for
5
+ * example); decorators applied through one copy must be visible to the other.
6
+ */
7
+ type Shared = {
8
+ /** Class → key → data of the class decorators. */
9
+ formProperties: WeakMap<object, Map<string, unknown>>;
10
+ /** Class → key → property → data of the property decorators. */
11
+ formItemProperties: WeakMap<object, Map<string, Record<string, unknown>>>;
12
+ /** The default form item register, created on first use. */
13
+ register?: FormItemRegister;
14
+ /** Whether forms report to the DevTools extension. */
15
+ devTools: boolean;
16
+ /** Service instances that were given to a controller. */
17
+ usedServices: WeakSet<object>;
18
+ };
19
+ export declare const shared: Shared;
20
+ export {};
@@ -1,2 +1,3 @@
1
1
  export { DEVTOOLS_MESSAGE_SOURCE, DEVTOOLS_PROTOCOL_VERSION, disableDevTools, enableDevTools, isDevToolsEnabled } from './devtools';
2
2
  export * from './deepCopy';
3
+ export * from './path';
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Reads the value at a path inside an object.
3
+ * @returns The value, or `undefined` when the path does not exist
4
+ */
5
+ export declare const readPropertyPath: (entity: unknown, path: string) => unknown;
6
+ /**
7
+ * Writes a value at a path inside an object, creating the objects and
8
+ * arrays on the way that do not exist yet.
9
+ */
10
+ export declare const writeToPropertyPath: (entity: object, path: string, value: unknown) => void;
@@ -1 +1 @@
1
- {"version":"2.0.0"}
1
+ {"version":"2.1.0"}
@@ -8,6 +8,8 @@ export declare class SetValue<E, F extends FormItem<E> = FormItem<E>> implements
8
8
  initialize(command: CommandService<E, F>): void;
9
9
  /**
10
10
  * Fires UPDATE_ITEM with the changed item and the items its control returned.
11
+ * When the property is set again, or the form is reset, while the control
12
+ * function is still running, the result of that older run is dropped.
11
13
  * @throws When the form has no item for the property
12
14
  */
13
15
  run(property: keyof E, value: unknown): Promise<void>;
@@ -1,7 +1,7 @@
1
1
  import { IServiceCommand } from '@punica/form';
2
2
  /**
3
3
  * What `Store` adds to the command of the functions of form items:
4
- * `validation: ({ readStoreItem }: CommandItem<E, F, StoreCommand>) => …`
4
+ * `validation: async ({ readStoreItem }: CommandItem<E, FormItem<E>, StoreCommand>) => …`
5
5
  */
6
6
  export type StoreCommand = {
7
7
  readStoreItem: (key: string) => unknown;
@@ -1,7 +1,13 @@
1
- import { CommandService, FormItem } from '@punica/form';
1
+ import { CommandService, ErrorDetail, FormItem } from '@punica/form';
2
2
  /**
3
3
  * Runs the validation of an item.
4
- * @returns The item with the result of the validation, or `undefined` when
5
- * the item is not validated (no validation function, or hidden)
4
+ * @returns The result of the validation, or `undefined` when the item is not
5
+ * validated (no validation function, or hidden)
6
6
  */
7
- export declare const validateItem: <E, F extends FormItem<E>>(command: CommandService<E, F>, item: F) => Promise<F | undefined>;
7
+ export declare const validateItem: <E, F extends FormItem<E>>(command: CommandService<E, F>, item: F) => Promise<ErrorDetail | undefined>;
8
+ /**
9
+ * Writes validation results onto the items as they are now: an item may
10
+ * have changed while the form was validated, and only its error state is
11
+ * what the validation knows.
12
+ */
13
+ export declare const writeResults: <E, F extends FormItem<E>>(command: CommandService<E, F>, results: Map<keyof E, ErrorDetail>) => void;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@punica/form-mcp",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "description": "MCP server for Punica Form: look up the exact API, read the rules and check code that uses it.",
5
5
  "keywords": [
6
6
  "mcp",
@@ -31,15 +31,16 @@
31
31
  "node": ">=20.12"
32
32
  },
33
33
  "publishConfig": {
34
- "access": "public"
34
+ "access": "public",
35
+ "provenance": true
35
36
  },
36
37
  "dependencies": {
37
38
  "@modelcontextprotocol/sdk": "^1.32.2",
38
39
  "zod": "^4.6.7"
39
40
  },
40
41
  "devDependencies": {
41
- "@punica/form": "^2.0.0",
42
- "@punica/form-service": "^2.0.0"
42
+ "@punica/form": "^2.1.0",
43
+ "@punica/form-service": "^2.1.0"
43
44
  },
44
45
  "scripts": {
45
46
  "build": "node build.mjs",
package/src/create.mjs CHANGED
@@ -20,10 +20,16 @@ export function createPunicaFormServer({ packages, guide }) {
20
20
  .map((pkg) => `${pkg.name} ${pkg.version} (${pkg.installed ? 'installed in this project' : 'not installed, bundled copy'})`)
21
21
  .join(', ');
22
22
 
23
+ // The guide describes 2.x; a project on 1.x must not be steered into it
24
+ const legacy = packages.find((pkg) => parseInt(pkg.version) < 2);
25
+ const legacyNote = legacy
26
+ ? `This project has ${legacy.name} ${legacy.version} installed, but this server documents Punica Form 2. search_api and get_api show the installed 1.x API and are correct; get_guide describes 2.x and applies only after upgrading. Do not rewrite 1.x code to the 2.x API unless the user asks to upgrade.\n\n`
27
+ : '';
28
+
23
29
  const server = new McpServer(
24
30
  { name: 'punica-form', version: '0.2.0' },
25
31
  {
26
- instructions: `${versions}. Punica Form is a headless form engine and is rarely in training data: never write an import, a service name or a method from memory. Read get_guide first, look names up with search_api and get_api, and check the code with validate_code before handing it over.`
32
+ instructions: `${legacyNote}${versions}. Punica Form is a headless form engine and is rarely in training data: never write an import, a service name or a method from memory. Read get_guide first, look names up with search_api and get_api, and check the code with validate_code before handing it over.`
27
33
  }
28
34
  );
29
35
 
@@ -36,7 +42,7 @@ export function createPunicaFormServer({ packages, guide }) {
36
42
  inputSchema: {},
37
43
  annotations: { readOnlyHint: true }
38
44
  },
39
- async () => text(guide)
45
+ async () => text(legacyNote + guide)
40
46
  );
41
47
 
42
48
  server.registerTool(
package/src/guide.md CHANGED
@@ -47,7 +47,16 @@ controller.getForm(); // the current form
47
47
  const unsubscribe = controller.subscribe(() => {}); // after every change
48
48
  ```
49
49
 
50
- In React: `useSyncExternalStore(controller.subscribe, controller.getForm)`.
50
+ In React use `@punica/form-react`:
51
+
52
+ ```tsx
53
+ const { controller, error } = useFormController(() => new UserForm());
54
+ // controller is undefined while the form is being started
55
+ const form = useForm(controller); // in a component that has the controller
56
+ ```
57
+
58
+ Without that package: `useSyncExternalStore(controller.subscribe, controller.getForm)`.
59
+ `start()` publishes the started form the same way (since 2.1).
51
60
  Never change a form or an item in place; use the services.
52
61
 
53
62
  ## Services
@@ -79,7 +88,12 @@ if (await controller.getService(Validate).run()) {
79
88
  ```
80
89
 
81
90
  - A service works only when it is listed in `@Services([...])`;
82
- `getService` throws for a class that is not.
91
+ `getService` throws for a class that is not, and before `start()`.
92
+ - List service classes (`@Services([GetValues, SetValue])`, since 2.1): every
93
+ form then gets its own services. With 2.0 pass instances
94
+ (`new GetValues()`); instances are shared by all forms of the class.
95
+ - `controller.batch(() => { … })` notifies subscribers once for several
96
+ changes (since 2.1).
83
97
  - There is no `getServices('name')`, no `validate(form)`, no
84
98
  `item.setValue(…)` and no `validateItem(…)`.
85
99
  - `Validate.run()` returns `false` when the form is invalid. Other failures
@@ -152,7 +166,7 @@ import { FormItemInputText, Reader, Title } from "./formSystem";
152
166
 
153
167
  @Title("Create User")
154
168
  @Readers([new Reader()])
155
- @Services([new GetValues(), new SetValue(), new Validate(), new Trigger()])
169
+ @Services([GetValues, SetValue, Validate, Trigger])
156
170
  export class UserForm {
157
171
  @FormItemInputText({
158
172
  label: "Name",
package/src/validate.mjs CHANGED
@@ -67,6 +67,10 @@ export function createValidator(knowledge) {
67
67
  }
68
68
  ];
69
69
 
70
+ // The rules name what 2.0 removed; for a project that still has 1.x
71
+ // installed that API is correct, so only its imports are checked
72
+ const isLegacy = knowledge.packages.some((pkg) => parseInt(pkg.version) < 2);
73
+
70
74
  /**
71
75
  * @param {string} code
72
76
  * @returns {Array<{ line: number, rule: string, message: string, fix: string }>}
@@ -98,7 +102,7 @@ export function createValidator(knowledge) {
98
102
  }
99
103
  }
100
104
 
101
- for (const { rule, pattern, message, fix } of rules) {
105
+ for (const { rule, pattern, message, fix } of isLegacy ? [] : rules) {
102
106
  for (const match of code.matchAll(pattern)) {
103
107
  add(match.index, rule, typeof message === 'string' ? message : message(match), fix(match));
104
108
  }