Form Filling Tool
Create a tool that fills form fields—one of the most common use cases.
The Pattern
- Select DOM elements
- Set their values
- Dispatch input events (for framework reactivity)
- Return success/failure
Example: Contact Form Tool
import '@mcp-b/global';
navigator.modelContext.registerTool({ name: 'fill_contact_form', description: 'Fill out the contact form with user information', inputSchema: { type: 'object', properties: { name: { type: 'string', description: 'Full name' }, email: { type: 'string', description: 'Email address' }, message: { type: 'string', description: 'Message content' }, }, required: ['name', 'email', 'message'], }, execute: async ({ name, email, message }) => { const nameInput = document.querySelector<HTMLInputElement>('#name'); const emailInput = document.querySelector<HTMLInputElement>('#email'); const messageInput = document.querySelector<HTMLTextAreaElement>('#message');
if (!nameInput || !emailInput || !messageInput) { return { content: [{ type: 'text', text: 'Form fields not found' }] }; }
// Set values and trigger events [ [nameInput, name], [emailInput, email], [messageInput, message], ].forEach(([el, value]) => { (el as HTMLInputElement).value = value as string; el.dispatchEvent(new Event('input', { bubbles: true })); });
return { content: [{ type: 'text', text: 'Form filled successfully' }] }; },});Important: Event Dispatching
Frameworks don’t detect direct .value changes. Dispatch events:
el.dispatchEvent(new Event('input', { bubbles: true }));Try it
The app has a contact form. Create a tool to fill it, then ask the agent to fill it with test data.
Files
Preparing Environment
- npm install
- npm run dev