Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(toolbar): add field notes mode (#62674)

Adam Leith7506ee4f213e
diff --git a/.semgrep/rules/idor-team-scoped-models.yaml b/.semgrep/rules/idor-team-scoped-models.yaml
index 36e61f448501..0e9e673e4291 100644
--- a/.semgrep/rules/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/idor-team-scoped-models.yaml
@@ -136,6 +136,7 @@ rules:
|TeamFeatureFlagDefaultsConfig
|TeamSessionSummariesConfig
|TeamWorkflowsConfig
+ |FieldNote
|FileSystem
|FileSystemFolderInstructions
|GithubCommentMapping
@@ -379,6 +380,7 @@ rules:
|TeamFeatureFlagDefaultsConfig
|TeamSessionSummariesConfig
|TeamWorkflowsConfig
+ |FieldNote
|FileSystem
|FileSystemFolderInstructions
|GithubCommentMapping
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index fdd436333762..0e871ea1d075 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -307,6 +307,7 @@ export const FEATURE_FLAGS = {
FEATURE_FLAG_NOTIFICATIONS: 'feature-flag-notifications', // owner: @reecejones #team-platform-features
FEATURE_FLAG_USAGE_DASHBOARD_CHECKBOX: 'feature-flag-usage-dashboard-checkbox', // owner: #team-feature-flags, globally disabled, enables opt-out of auto dashboard creation
FEATURE_FLAGS_ACROSS_PROJECTS_INDEX: 'feature-flags-across-projects-index', // owner: #team-platform-features
+ FIELD_NOTES: 'field-notes', // owner: @adamleith
FLAG_EVALUATION_RUNTIMES: 'flag-evaluation-runtimes', // owner: @dmarticus #team-feature-flags
FLAG_EVALUATION_TAGS: 'flag-evaluation-tags', // owner: @dmarticus #team-feature-flags
FLAGGED_FEATURE_INDICATOR: 'flagged-feature-indicator', // owner: @benjackwhite
diff --git a/frontend/src/lib/scopes.tsx b/frontend/src/lib/scopes.tsx
index 58dc0edb7ea8..ed2e9bc8f744 100644
--- a/frontend/src/lib/scopes.tsx
+++ b/frontend/src/lib/scopes.tsx
@@ -122,6 +122,7 @@ export const API_SCOPES: APIScope[] = [
{ key: 'survey', objectName: 'Survey', objectPlural: 'surveys' },
{ key: 'ticket', objectName: 'Ticket', objectPlural: 'tickets' },
{ key: 'tracing', objectName: 'Tracing', objectPlural: 'tracing' },
+ { key: 'field_note', objectName: 'Field note', objectPlural: 'field notes' },
{ key: 'uploaded_media', objectName: 'Uploaded media', objectPlural: 'uploaded media' },
{ key: 'usage_metric', objectName: 'Usage metric', objectPlural: 'usage metrics' },
{
diff --git a/frontend/src/toolbar/bar/Toolbar.scss b/frontend/src/toolbar/bar/Toolbar.scss
index 61b01ba4d55a..dca822d5f0e2 100644
--- a/frontend/src/toolbar/bar/Toolbar.scss
+++ b/frontend/src/toolbar/bar/Toolbar.scss
@@ -153,6 +153,10 @@
--toolbar-width-expanded: 460px;
}
+ &--extra-buttons-4 {
+ --toolbar-width-expanded: 502px;
+ }
+
&--minimized {
width: var(--toolbar-width-minimized); // Account for border
diff --git a/frontend/src/toolbar/bar/Toolbar.tsx b/frontend/src/toolbar/bar/Toolbar.tsx
index 0ff1ba4e0e12..7ff3b6151984 100644
--- a/frontend/src/toolbar/bar/Toolbar.tsx
+++ b/frontend/src/toolbar/bar/Toolbar.tsx
@@ -6,6 +6,7 @@ import { PostHog } from 'posthog-js'
import { useEffect, useRef, useState } from 'react'
import {
+ IconApp,
IconBolt,
IconCamera,
IconCheck,
@@ -43,6 +44,9 @@ import { toolbarLogic } from '~/toolbar/bar/toolbarLogic'
import { UiHostConfigModal } from '~/toolbar/bar/UiHostConfigModal'
import { EventDebugMenu } from '~/toolbar/debug/EventDebugMenu'
import { ExperimentsToolbarMenu } from '~/toolbar/experiments/ExperimentsToolbarMenu'
+import { fieldNotesLogic } from '~/toolbar/field-notes/fieldNotesLogic'
+import { FieldNotesOverlay } from '~/toolbar/field-notes/FieldNotesOverlay'
+import { FieldNotesToolbarMenu } from '~/toolbar/field-notes/FieldNotesToolbarMenu'
import { FlagsToolbarMenu } from '~/toolbar/flags/FlagsToolbarMenu'
import { productToursLogic } from '~/toolbar/product-tours/productToursLogic'
import { ProductToursSidebar } from '~/toolbar/product-tours/ProductToursSidebar'
@@ -325,6 +329,9 @@ export function ToolbarInfoMenu(): JSX.Element | null {
const surveysFlag = useToolbarFeatureFlag('surveys-toolbar')
const showSurveys = surveysFlag
+ const fieldNotesFlag = useToolbarFeatureFlag('field-notes')
+ const showFieldNotes = inStorybook() || inStorybookTestRunner() || fieldNotesFlag
+
const content = minimized ? null : visibleMenu === 'flags' ? (
<FlagsToolbarMenu />
) : visibleMenu === 'heatmap' ? (
@@ -339,6 +346,8 @@ export function ToolbarInfoMenu(): JSX.Element | null {
<ExperimentsToolbarMenu />
) : visibleMenu === 'product-tours' && showProductTours ? (
<ProductToursToolbarMenu />
+ ) : visibleMenu === 'field-notes' && showFieldNotes ? (
+ <FieldNotesToolbarMenu />
) : visibleMenu === 'surveys' && showSurveys ? (
<SurveysToolbarMenu />
) : null
@@ -399,6 +408,10 @@ export function Toolbar(): JSX.Element | null {
const surveysFlag = useToolbarFeatureFlag('surveys-toolbar')
const showSurveys = surveysFlag
+ const fieldNotesFlag = useToolbarFeatureFlag('field-notes')
+ const showFieldNotes = inStorybook() || inStorybookTestRunner() || fieldNotesFlag
+ const { hasOpenedFieldNotes } = useValues(fieldNotesLogic)
+
useEffect(() => {
setElement(ref.current)
return () => setElement(null)
@@ -438,6 +451,7 @@ export function Toolbar(): JSX.Element | null {
return (
<>
{showToursSidebar && <ProductToursSidebar />}
+ {showFieldNotes && <FieldNotesOverlay />}
{isSurveyCreating && <SurveySidebar />}
<ToolbarInfoMenu />
<div
@@ -446,9 +460,14 @@ export function Toolbar(): JSX.Element | null {
'Toolbar--minimized': minimized,
'Toolbar--hedgehog-mode': hedgehogMode,
'Toolbar--dragging': isDragging,
- 'Toolbar--extra-buttons-1': 1 + (showProductTours ? 1 : 0) + (showSurveys ? 1 : 0) === 1,
- 'Toolbar--extra-buttons-2': 1 + (showProductTours ? 1 : 0) + (showSurveys ? 1 : 0) === 2,
- 'Toolbar--extra-buttons-3': 1 + (showProductTours ? 1 : 0) + (showSurveys ? 1 : 0) === 3,
+ 'Toolbar--extra-buttons-1':
+ 1 + (showProductTours ? 1 : 0) + (showFieldNotes ? 1 : 0) + (showSurveys ? 1 : 0) === 1,
+ 'Toolbar--extra-buttons-2':
+ 1 + (showProductTours ? 1 : 0) + (showFieldNotes ? 1 : 0) + (showSurveys ? 1 : 0) === 2,
+ 'Toolbar--extra-buttons-3':
+ 1 + (showProductTours ? 1 : 0) + (showFieldNotes ? 1 : 0) + (showSurveys ? 1 : 0) === 3,
+ 'Toolbar--extra-buttons-4':
+ 1 + (showProductTours ? 1 : 0) + (showFieldNotes ? 1 : 0) + (showSurveys ? 1 : 0) === 4,
})}
onMouseDown={(e) => onMouseOrTouchDown(e.nativeEvent)}
onTouchStart={(e) => onMouseOrTouchDown(e.nativeEvent)}
@@ -477,9 +496,27 @@ export function Toolbar(): JSX.Element | null {
<ToolbarButton menuId="inspect">
<IconSearch />
</ToolbarButton>
- <ToolbarButton menuId="heatmap">
- <IconCursorClick />
- </ToolbarButton>
+ {/* When the field notes flag is on, field notes takes the heatmap slot + cursor icon */}
+ {showFieldNotes ? (
+ <ToolbarButton menuId="field-notes" title="Field notes">
+ {/* Inline font-size because the wrapper breaks the `button > svg` size rule */}
+ {/* eslint-disable-next-line react/forbid-dom-props */}
+ <span className="relative flex" style={{ fontSize: '1.5rem' }}>
+ <IconCursorClick />
+ {!hasOpenedFieldNotes && (
+ <span
+ className="absolute -top-1 -right-1 w-2 h-2 rounded-full"
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{ backgroundColor: 'var(--primary-3000)' }}
+ />
+ )}
+ </span>
+ </ToolbarButton>
+ ) : (
+ <ToolbarButton menuId="heatmap">
+ <IconCursorClick />
+ </ToolbarButton>
+ )}
<ToolbarButton menuId="actions">
<IconBolt />
</ToolbarButton>
@@ -500,6 +537,12 @@ export function Toolbar(): JSX.Element | null {
<IconSpotlight />
</ToolbarButton>
)}
+ {/* Heatmaps moves here and takes the app icon when field notes is enabled */}
+ {showFieldNotes && (
+ <ToolbarButton menuId="heatmap" title="Heatmaps">
+ <IconApp />
+ </ToolbarButton>
+ )}
{showSurveys && (
<ToolbarButton menuId="surveys" title="Surveys">
<IconMessage />
diff --git a/frontend/src/toolbar/bar/toolbarLogic.ts b/frontend/src/toolbar/bar/toolbarLogic.ts
index 63b2c63616e8..5575c9af65a3 100644
--- a/frontend/src/toolbar/bar/toolbarLogic.ts
+++ b/frontend/src/toolbar/bar/toolbarLogic.ts
@@ -12,6 +12,7 @@ import { elementsLogic } from '~/toolbar/elements/elementsLogic'
import { heatmapToolbarMenuLogic } from '~/toolbar/elements/heatmapToolbarMenuLogic'
import { experimentsLogic } from '~/toolbar/experiments/experimentsLogic'
import { experimentsTabLogic } from '~/toolbar/experiments/experimentsTabLogic'
+import { fieldNotesLogic } from '~/toolbar/field-notes/fieldNotesLogic'
import { flagsToolbarLogic } from '~/toolbar/flags/flagsToolbarLogic'
import { productToursLogic } from '~/toolbar/product-tours/productToursLogic'
import { surveysToolbarLogic } from '~/toolbar/surveys/surveysToolbarLogic'
@@ -41,6 +42,7 @@ export type MenuState =
| 'web-vitals'
| 'product-tours'
| 'surveys'
+ | 'field-notes'
export type ToolbarPositionType =
| 'top-left'
@@ -93,6 +95,8 @@ export const toolbarLogic = kea<toolbarLogicType>([
['enableInspect', 'disableInspect', 'createAction'],
productToursLogic,
['showButtonProductTours', 'hideButtonProductTours'],
+ fieldNotesLogic,
+ ['showButtonFieldNotes', 'hideButtonFieldNotes'],
surveysToolbarLogic,
['showButtonSurveys', 'hideButtonSurveys'],
heatmapToolbarMenuLogic,
@@ -464,6 +468,7 @@ export const toolbarLogic = kea<toolbarLogicType>([
actions.disableHeatmap()
actions.hideButtonActions()
actions.hideButtonProductTours()
+ actions.hideButtonFieldNotes()
actions.hideButtonSurveys()
if (visibleMenu === 'heatmap') {
@@ -478,6 +483,8 @@ export const toolbarLogic = kea<toolbarLogicType>([
actions.enableInspect()
} else if (visibleMenu === 'product-tours') {
actions.showButtonProductTours()
+ } else if (visibleMenu === 'field-notes') {
+ actions.showButtonFieldNotes()
} else if (visibleMenu === 'surveys') {
actions.showButtonSurveys()
}
diff --git a/frontend/src/toolbar/field-notes/FieldNotesOverlay.tsx b/frontend/src/toolbar/field-notes/FieldNotesOverlay.tsx
new file mode 100644
index 000000000000..977b94a4ab3f
--- /dev/null
+++ b/frontend/src/toolbar/field-notes/FieldNotesOverlay.tsx
@@ -0,0 +1,124 @@
+import { useActions, useValues } from 'kea'
+
+import { IconX } from '@posthog/icons'
+import { LemonButton, LemonTextArea } from '@posthog/lemon-ui'
+
+import { ElementHighlight } from '~/toolbar/product-tours/ElementHighlight'
+
+import { fieldNotesLogic } from './fieldNotesLogic'
+
+const COMMENT_BOX_WIDTH = 320
+
+// Always-mounted overlay: draws the hover/selected highlights, the "click an element"
+// banner during selection, and the comment box anchored to the selected element. Living
+// here (not in the toolbar menu popup) decouples it from the menu's open/close/blur
+// lifecycle, so selecting an element reliably opens the write box.
+export function FieldNotesOverlay(): JSX.Element | null {
+ const { isFieldNoting, hoverElementRect, selectedElementRect, selectedElement, comment, submitResultLoading } =
+ useValues(fieldNotesLogic)
+ const { stopFieldNote, setComment, submitFieldNote, clearSelection } = useActions(fieldNotesLogic)
+
+ if (!isFieldNoting && !selectedElement) {
+ return null
+ }
+
+ // Anchor the comment box just below the element, clamped into the viewport.
+ let boxTop = 80
+ let boxLeft = 16
+ if (selectedElementRect) {
+ boxTop = Math.max(
+ 8,
+ Math.min(selectedElementRect.top + selectedElementRect.height + 8, window.innerHeight - 240)
+ )
+ boxLeft = Math.min(Math.max(selectedElementRect.left, 8), window.innerWidth - COMMENT_BOX_WIDTH - 8)
+ }
+
+ return (
+ <>
+ {selectedElementRect && <ElementHighlight rect={selectedElementRect} isSelected />}
+ {isFieldNoting && hoverElementRect && <ElementHighlight rect={hoverElementRect} />}
+
+ {isFieldNoting && !selectedElement && (
+ <div
+ className="fixed flex items-center gap-3 text-white text-sm font-medium"
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{
+ left: '50%',
+ transform: 'translateX(-50%)',
+ top: 16,
+ paddingLeft: 16,
+ paddingRight: 8,
+ paddingTop: 10,
+ paddingBottom: 10,
+ borderRadius: 999,
+ backgroundColor: 'var(--primary-3000)',
+ boxShadow: '0 4px 12px rgba(29, 74, 255, 0.3)',
+ zIndex: 2147483020,
+ pointerEvents: 'auto',
+ }}
+ >
+ <span>Click an element to add a note</span>
+ <button
+ type="button"
+ onClick={() => stopFieldNote()}
+ className="p-1.5 rounded-full border-none cursor-pointer flex items-center justify-center"
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{ background: 'rgba(255, 255, 255, 0.2)', color: '#fff' }}
+ >
+ <IconX className="w-4 h-4" />
+ </button>
+ </div>
+ )}
+
+ {selectedElement && (
+ <div
+ className="fixed flex flex-col gap-2 p-3 rounded shadow-xl"
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{
+ top: boxTop,
+ left: boxLeft,
+ width: COMMENT_BOX_WIDTH,
+ backgroundColor: 'var(--color-bg-3000, #1d1f27)',
+ color: 'var(--text-3000, #fff)',
+ border: '1px solid var(--border-bold-3000, #3f4150)',
+ zIndex: 2147483021,
+ pointerEvents: 'auto',
+ }}
+ onClick={(e) => e.stopPropagation()}
+ >
+ <div className="text-xs font-semibold uppercase opacity-70">New field note</div>
+ <LemonTextArea
+ placeholder="What should change about this element? (⌘↵ to save)"
+ value={comment}
+ onChange={setComment}
+ onPressCmdEnter={() => comment.trim() && !submitResultLoading && submitFieldNote()}
+ minRows={3}
+ autoFocus
+ />
+ <div className="flex gap-2">
+ <LemonButton
+ type="secondary"
+ size="small"
+ onClick={() => clearSelection()}
+ className="flex-1"
+ center
+ >
+ Cancel
+ </LemonButton>
+ <LemonButton
+ type="primary"
+ size="small"
+ onClick={() => submitFieldNote()}
+ loading={submitResultLoading}
+ disabledReason={!comment.trim() ? 'Write a comment first' : undefined}
+ className="flex-1"
+ center
+ >
+ Save
+ </LemonButton>
+ </div>
+ </div>
+ )}
+ </>
+ )
+}
diff --git a/frontend/src/toolbar/field-notes/FieldNotesToolbarMenu.tsx b/frontend/src/toolbar/field-notes/FieldNotesToolbarMenu.tsx
new file mode 100644
index 000000000000..f2a36135b043
--- /dev/null
+++ b/frontend/src/toolbar/field-notes/FieldNotesToolbarMenu.tsx
@@ -0,0 +1,74 @@
+import { useActions, useValues } from 'kea'
+
+import { IconCursorClick, IconTrash } from '@posthog/icons'
+import { LemonButton } from '@posthog/lemon-ui'
+
+import { Spinner } from 'lib/lemon-ui/Spinner'
+
+import { ToolbarMenu } from '~/toolbar/bar/ToolbarMenu'
+
+import { fieldNotesLogic } from './fieldNotesLogic'
+
+export function FieldNotesToolbarMenu(): JSX.Element {
+ const { fieldNotes, fieldNotesLoading, isFieldNoting, deletingId } = useValues(fieldNotesLogic)
+ const { startFieldNote, stopFieldNote, deleteFieldNote } = useActions(fieldNotesLogic)
+
+ return (
+ <ToolbarMenu>
+ <ToolbarMenu.Header className="pt-2">
+ <span className="block px-2 pt-3">Field notes</span>
+ </ToolbarMenu.Header>
+ <ToolbarMenu.Body>
+ <div className="px-2 pb-2 space-y-3">
+ <p className="text-xs text-muted mt-0 mb-4">
+ Point at any element and leave a note. Your AI coding agent can read these over PostHog's MCP
+ and can turn them into changes — then mark them resolved.
+ </p>
+ <p className="text-xs text-muted mt-0 mb-4">
+ Ask your agent for your <strong>project's Field notes</strong> to get the list.
+ </p>
+ <LemonButton
+ type="primary"
+ fullWidth
+ center
+ icon={<IconCursorClick />}
+ onClick={() => (isFieldNoting ? stopFieldNote() : startFieldNote())}
+ >
+ {isFieldNoting ? 'Cancel — click an element…' : 'Add a field note'}
+ </LemonButton>
+
+ <div className="space-y-1">
+ <div className="text-xs font-medium text-muted uppercase">Pending</div>
+ {fieldNotesLoading ? (
+ <div className="flex justify-center py-4">
+ <Spinner />
+ </div>
+ ) : fieldNotes.length > 0 ? (
+ fieldNotes.map((note) => (
+ <div
+ key={note.id}
+ className="rounded border border-border p-2 text-sm bg-bg-light flex items-start gap-2"
+ >
+ <div className="flex-1 min-w-0">
+ <div className="truncate">{note.comment}</div>
+ <div className="text-muted text-xs truncate">{note.selector}</div>
+ </div>
+ <LemonButton
+ size="xsmall"
+ icon={<IconTrash />}
+ tooltip="Delete field note"
+ loading={deletingId === note.id}
+ disabledReason={deletingId === note.id ? 'Deleting…' : undefined}
+ onClick={() => deleteFieldNote(note.id)}
+ />
+ </div>
+ ))
+ ) : (
+ <p className="text-muted text-sm text-center py-2">No pending field notes</p>
+ )}
+ </div>
+ </div>
+ </ToolbarMenu.Body>
+ </ToolbarMenu>
+ )
+}
diff --git a/frontend/src/toolbar/field-notes/fieldNotesLogic.ts b/frontend/src/toolbar/field-notes/fieldNotesLogic.ts
new file mode 100644
index 000000000000..46a28ec42bfb
--- /dev/null
+++ b/frontend/src/toolbar/field-notes/fieldNotesLogic.ts
@@ -0,0 +1,332 @@
+import { actions, connect, events, kea, listeners, path, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { lemonToast } from 'lib/lemon-ui/LemonToast'
+
+import { inferSelector } from '~/toolbar/product-tours/elementInference'
+import { toolbarConfigLogic, toolbarFetch } from '~/toolbar/toolbarConfigLogic'
+import { toolbarLogger } from '~/toolbar/toolbarLogger'
+import { captureToolbarException, toolbarPosthogJS } from '~/toolbar/toolbarPosthogJS'
+import { ElementRect } from '~/toolbar/types'
+import { TOOLBAR_ID, elementToActionStep, getRectForElement, joinWithUiHost } from '~/toolbar/utils'
+import { captureAndUploadElementScreenshot } from '~/toolbar/utils/screenshot'
+
+import type { fieldNotesLogicType } from './fieldNotesLogicType'
+
+export interface PageContext {
+ url: string
+ host: string
+ pathname: string
+ viewport: { width: number; height: number }
+}
+
+function capturePageContext(): PageContext {
+ // Drop the query string and fragment — they can carry one-time tokens (reset, OAuth, session)
+ // that would otherwise be persisted and surfaced to anyone with field note read access.
+ return {
+ url: `${window.location.origin}${window.location.pathname}`,
+ host: window.location.host,
+ pathname: window.location.pathname,
+ viewport: { width: window.innerWidth, height: window.innerHeight },
+ }
+}
+
+export interface FieldNote {
+ id: string
+ comment: string
+ field_note_status: 'pending' | 'acknowledged' | 'resolved' | 'dismissed'
+ resolution: string | null
+ url: string
+ host: string
+ pathname: string | null
+ selector: string
+ element_text: string | null
+ screenshot_url: string | null
+ created_at: string
+}
+
+function isToolbarElement(element: HTMLElement): boolean {
+ const toolbar = document.getElementById(TOOLBAR_ID)
+ return toolbar?.contains(element) ?? false
+}
+
+export const fieldNotesLogic = kea<fieldNotesLogicType>([
+ path(['toolbar', 'field-notes', 'fieldNotesLogic']),
+
+ connect(() => ({
+ values: [toolbarConfigLogic, ['dataAttributes', 'uiHost']],
+ })),
+
+ actions({
+ showButtonFieldNotes: true,
+ hideButtonFieldNotes: true,
+ startFieldNote: true,
+ stopFieldNote: true,
+ setHoverElement: (element: HTMLElement | null) => ({ element }),
+ // Snapshot the page context at select time — on an SPA the URL can change before save.
+ selectElement: (element: HTMLElement) => ({ element, page: capturePageContext() }),
+ clearSelection: true,
+ setComment: (comment: string) => ({ comment }),
+ setScreenshotUrl: (url: string | null) => ({ url }),
+ deleteFieldNote: (id: string) => ({ id }),
+ updateRects: true,
+ }),
+
+ loaders(({ values }) => ({
+ fieldNotes: [
+ [] as FieldNote[],
+ {
+ loadFieldNotes: async () => {
+ const response = await toolbarFetch('/api/projects/@current/field_notes/?field_note_status=pending')
+ if (!response.ok) {
+ return values.fieldNotes
+ }
+ const data = await response.json()
+ return data.results ?? data
+ },
+ },
+ ],
+ })),
+
+ reducers({
+ buttonFieldNotesVisible: [
+ false,
+ {
+ showButtonFieldNotes: () => true,
+ hideButtonFieldNotes: () => false,
+ },
+ ],
+ isFieldNoting: [
+ false,
+ {
+ startFieldNote: () => true,
+ stopFieldNote: () => false,
+ selectElement: () => false,
+ hideButtonFieldNotes: () => false,
+ },
+ ],
+ hoverElement: [
+ null as HTMLElement | null,
+ {
+ setHoverElement: (_, { element }) => element,
+ stopFieldNote: () => null,
+ selectElement: () => null,
+ hideButtonFieldNotes: () => null,
+ },
+ ],
+ selectedElement: [
+ null as HTMLElement | null,
+ {
+ selectElement: (_, { element }) => element,
+ clearSelection: () => null,
+ // Closing/switching the menu closes the comment box (no cascade: select no longer calls setVisibleMenu).
+ hideButtonFieldNotes: () => null,
+ },
+ ],
+ comment: [
+ '',
+ {
+ setComment: (_, { comment }) => comment,
+ clearSelection: () => '',
+ hideButtonFieldNotes: () => '',
+ submitFieldNoteSuccess: () => '',
+ },
+ ],
+ pageContext: [
+ null as PageContext | null,
+ {
+ selectElement: (_, { page }) => page,
+ clearSelection: () => null,
+ hideButtonFieldNotes: () => null,
+ },
+ ],
+ screenshotUrl: [
+ null as string | null,
+ {
+ setScreenshotUrl: (_, { url }) => url,
+ selectElement: () => null,
+ clearSelection: () => null,
+ hideButtonFieldNotes: () => null,
+ },
+ ],
+ rectUpdateCounter: [
+ 0,
+ {
+ updateRects: (state) => state + 1,
+ },
+ ],
+ // Drives the "new" badge on the toolbar button — dismissed (persistently) once the menu is first opened.
+ hasOpenedFieldNotes: [
+ false,
+ { persist: true },
+ {
+ showButtonFieldNotes: () => true,
+ },
+ ],
+ // Id of the field note currently being deleted, to disable its row button (no double-submit).
+ deletingId: [
+ null as string | null,
+ {
+ deleteFieldNote: (_, { id }) => id,
+ loadFieldNotesSuccess: () => null,
+ loadFieldNotesFailure: () => null,
+ },
+ ],
+ }),
+
+ selectors({
+ hoverElementRect: [
+ (s) => [s.hoverElement, s.rectUpdateCounter],
+ (hoverElement): ElementRect | null => (hoverElement ? getRectForElement(hoverElement) : null),
+ ],
+ selectedElementRect: [
+ (s) => [s.selectedElement, s.rectUpdateCounter],
+ (selectedElement): ElementRect | null => (selectedElement ? getRectForElement(selectedElement) : null),
+ ],
+ }),
+
+ loaders(({ values, actions }) => ({
+ submitResult: [
+ null as FieldNote | null,
+ {
+ submitFieldNote: async () => {
+ const { selectedElement, comment, dataAttributes, pageContext, screenshotUrl } = values
+ if (!selectedElement || !comment.trim()) {
+ return null
+ }
+ const selector = elementToActionStep(selectedElement, dataAttributes).selector ?? ''
+ const inferred = inferSelector(selectedElement)?.selector
+ const elementText = (selectedElement.textContent ?? '').trim().slice(0, 500) || null
+ const page = pageContext ?? capturePageContext()
+
+ const payload = {
+ comment: comment.trim(),
+ url: page.url,
+ host: page.host,
+ pathname: page.pathname,
+ selector,
+ element_text: elementText,
+ element_context: inferred ? { inferred } : {},
+ viewport: page.viewport,
+ ...(screenshotUrl ? { screenshot_url: screenshotUrl } : {}),
+ }
+
+ try {
+ const response = await toolbarFetch('/api/projects/@current/field_notes/', 'POST', payload)
+ if (!response.ok) {
+ const error = await response.json().catch(() => ({}))
+ toolbarLogger.error('field-notes', 'Save failed', {
+ status: response.status,
+ detail: error.detail,
+ })
+ lemonToast.error(
+ `Failed to save field note (${response.status})${error.detail ? `: ${error.detail}` : ''}`
+ )
+ return null
+ }
+ const saved = await response.json()
+ lemonToast.success('Field note saved')
+ actions.clearSelection()
+ actions.loadFieldNotes()
+ return saved
+ } catch (e: any) {
+ toolbarLogger.error('field-notes', 'Failed to save field note')
+ captureToolbarException(e, 'field_note_save')
+ lemonToast.error('Failed to save field note')
+ return null
+ }
+ },
+ },
+ ],
+ })),
+
+ listeners(({ actions, values }) => ({
+ showButtonFieldNotes: () => {
+ toolbarPosthogJS.capture('toolbar mode triggered', { mode: 'field-notes', enabled: true })
+ actions.loadFieldNotes()
+ },
+ hideButtonFieldNotes: () => {
+ toolbarPosthogJS.capture('toolbar mode triggered', { mode: 'field-notes', enabled: false })
+ },
+ // Capture a screenshot in the background while the user types — best-effort, never blocks save.
+ selectElement: async ({ element }) => {
+ try {
+ const { mediaId } = await captureAndUploadElementScreenshot(element)
+ actions.setScreenshotUrl(joinWithUiHost(values.uiHost, `/uploaded_media/${mediaId}`))
+ } catch (e: any) {
+ toolbarLogger.warn('field-notes', 'Failed to capture screenshot')
+ captureToolbarException(e, 'field_note_screenshot')
+ }
+ },
+ deleteFieldNote: async ({ id }) => {
+ const response = await toolbarFetch(`/api/projects/@current/field_notes/${id}/`, 'DELETE')
+ if (!response.ok && response.status !== 204) {
+ lemonToast.error(`Failed to delete field note (${response.status})`)
+ }
+ actions.loadFieldNotes()
+ },
+ })),
+
+ events(({ actions, values, cache }) => ({
+ afterMount: () => {
+ cache.onMouseOver = (e: MouseEvent): void => {
+ if (!values.isFieldNoting) {
+ return
+ }
+ const target = e.target as HTMLElement
+ if (target && !isToolbarElement(target)) {
+ actions.setHoverElement(target)
+ }
+ }
+ cache.onClick = (e: MouseEvent): void => {
+ if (!values.isFieldNoting) {
+ return
+ }
+ const target = e.target as HTMLElement
+ if (!target || isToolbarElement(target)) {
+ return
+ }
+ e.preventDefault()
+ e.stopPropagation()
+ actions.selectElement(target)
+ }
+ cache.onScroll = (): void => {
+ if (values.hoverElement || values.selectedElement) {
+ actions.updateRects()
+ }
+ }
+ cache.onResize = (): void => {
+ if (values.hoverElement || values.selectedElement) {
+ actions.updateRects()
+ }
+ }
+ cache.onKeyDown = (e: KeyboardEvent): void => {
+ if (e.key === 'Escape' && values.isFieldNoting) {
+ actions.stopFieldNote()
+ }
+ }
+ document.addEventListener('mouseover', cache.onMouseOver, true)
+ document.addEventListener('click', cache.onClick, true)
+ document.addEventListener('scroll', cache.onScroll, { capture: true, passive: true })
+ window.addEventListener('resize', cache.onResize)
+ window.addEventListener('keydown', cache.onKeyDown)
+ },
+ beforeUnmount: () => {
+ if (cache.onMouseOver) {
+ document.removeEventListener('mouseover', cache.onMouseOver, true)
+ }
+ if (cache.onClick) {
+ document.removeEventListener('click', cache.onClick, true)
+ }
+ if (cache.onScroll) {
+ document.removeEventListener('scroll', cache.onScroll, { capture: true })
+ }
+ if (cache.onResize) {
+ window.removeEventListener('resize', cache.onResize)
+ }
+ if (cache.onKeyDown) {
+ window.removeEventListener('keydown', cache.onKeyDown)
+ }
+ },
+ })),
+])
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index cb5f1c19de9d..eba5b37e30b1 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -5530,6 +5530,7 @@ export type APIScopeObject =
| 'web_analytics'
| 'webhook'
| 'tracing'
+ | 'field_note'
export type APIScopeAction = 'read' | 'write'
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index c76eb1a58ffb..d5572a595db0 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -2864,6 +2864,8 @@ importers:
specifier: 'catalog:'
+ products/field_notes: {}
+
products/games:
dependencies:
'@posthog/icons':
diff --git a/posthog/scopes.py b/posthog/scopes.py
index 4f7880f0e790..ff05db8ef85a 100644
--- a/posthog/scopes.py
+++ b/posthog/scopes.py
@@ -97,6 +97,7 @@ APIScopeObject = Literal[
"ticket",
"task",
"tracing",
+ "field_note",
"uploaded_media",
"usage_metric",
"user",
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 46e14dfc6f52..e07079602587 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -35,6 +35,7 @@ PRODUCTS_APPS = [
"products.early_access_features.backend.apps.EarlyAccessFeaturesConfig",
"products.tasks.backend.apps.TasksConfig",
"products.links.backend.apps.LinksConfig",
+ "products.field_notes.backend.apps.FieldNotesConfig",
"products.revenue_analytics.backend.apps.RevenueAnalyticsConfig",
"products.user_interviews.backend.apps.UserInterviewsConfig",
"products.ai_observability.backend.apps.AIObservabilityConfig",
@@ -840,6 +841,8 @@ TOOLBAR_OAUTH_SCOPES = [
"uploaded_media:write",
"survey:read",
"survey:write",
+ "field_note:read",
+ "field_note:write",
]
ELEMENT_STATS_DEFAULT_LIMIT = get_from_env("ELEMENT_STATS_DEFAULT_LIMIT", 50_000, type_cast=int)
diff --git a/products/field_notes/__init__.py b/products/field_notes/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/field_notes/backend/__init__.py b/products/field_notes/backend/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/field_notes/backend/api.py b/products/field_notes/backend/api.py
new file mode 100644
index 000000000000..031d655c51b4
--- /dev/null
+++ b/products/field_notes/backend/api.py
@@ -0,0 +1,171 @@
+from typing import Any
+
+from django.db.models import QuerySet
+
+import structlog
+from drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema_field, extend_schema_view
+from rest_framework import serializers, viewsets
+from rest_framework.exceptions import ValidationError
+from rest_framework.permissions import IsAuthenticated
+
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.api.shared import UserBasicSerializer
+from posthog.models.team.team import Team
+
+from products.field_notes.backend.models import FieldNote
+
+logger = structlog.get_logger(__name__)
+
+
+@extend_schema_field(
+ {
+ "type": "object",
+ "nullable": True,
+ "properties": {
+ "width": {"type": "integer", "description": "Viewport width in pixels."},
+ "height": {"type": "integer", "description": "Viewport height in pixels."},
+ },
+ }
+)
+class ViewportField(serializers.JSONField):
+ pass
+
+
+@extend_schema_field(
+ {
+ "type": "object",
+ "description": "Structured element metadata: inferred selectors, attributes, and component hints.",
+ "additionalProperties": True,
+ }
+)
+class ElementContextField(serializers.JSONField):
+ pass
+
+
+class FieldNoteSerializer(serializers.ModelSerializer):
+ created_by = UserBasicSerializer(read_only=True)
+ # Length caps on free-text fields — the toolbar runs on untrusted customer pages, so cap
+ # what it can POST to keep rows (and downstream MCP payloads) bounded.
+ comment = serializers.CharField(max_length=5000, help_text="The note the user wrote about the element.")
+ url = serializers.CharField(max_length=2048, help_text="Full URL of the page the field note was made on.")
+ host = serializers.CharField(max_length=255, help_text="Hostname of the page, used to scope field notes to a site.")
+ pathname = serializers.CharField(
+ max_length=2048, required=False, allow_null=True, allow_blank=True, help_text="Path portion of the URL."
+ )
+ selector = serializers.CharField(max_length=4096, help_text="CSS selector that locates the element on the page.")
+ element_text = serializers.CharField(
+ max_length=2048,
+ required=False,
+ allow_null=True,
+ allow_blank=True,
+ help_text="Visible text of the element, if any.",
+ )
+ element_chain = serializers.CharField(
+ max_length=20000,
+ required=False,
+ allow_null=True,
+ allow_blank=True,
+ help_text="Serialized autocapture-style element chain from the element up to the document root.",
+ )
+ field_note_status = serializers.ChoiceField(
+ choices=FieldNote.Status.choices,
+ required=False,
+ help_text="Lifecycle of the field note: pending, acknowledged, resolved, or dismissed. Ignored on create.",
+ )
+ screenshot_url = serializers.CharField(
+ max_length=2048,
+ required=False,
+ allow_null=True,
+ allow_blank=True,
+ help_text="URL of an uploaded screenshot captured with the field_note.",
+ )
+ element_context = ElementContextField(
+ required=False, help_text="Structured element metadata (inferred selectors, attributes, component hints)."
+ )
+ viewport = ViewportField(
+ required=False, allow_null=True, help_text="Viewport size when the field note was made, as {width, height}."
+ )
+
+ class Meta:
+ model = FieldNote
+ fields = [
+ "id",
+ "comment",
+ "field_note_status",
+ "resolution",
+ "url",
+ "host",
+ "pathname",
+ "selector",
+ "element_text",
+ "element_chain",
+ "element_context",
+ "viewport",
+ "screenshot_url",
+ "created_at",
+ "updated_at",
+ "created_by",
+ ]
+ read_only_fields = ["id", "created_at", "updated_at", "created_by"]
+
+ def create(self, validated_data: dict[str, Any]) -> FieldNote:
+ team = Team.objects.get(id=self.context["team_id"])
+ request = self.context["request"]
+ # Field notes are always born `pending`; status/resolution are agent-only and only
+ # settable via update — strip them so a write-scoped toolbar token can't forge a
+ # pre-resolved field note with a fabricated resolution note.
+ validated_data.pop("field_note_status", None)
+ validated_data.pop("resolution", None)
+ field_note = FieldNote.objects.create(
+ team=team,
+ created_by=request.user if request.user.is_authenticated else None,
+ **validated_data,
+ )
+ logger.info("field_note_created", id=field_note.id, team_id=team.id, host=field_note.host)
+ return field_note
+
+
+@extend_schema_view(
+ list=extend_schema(
+ parameters=[
+ OpenApiParameter(
+ "field_note_status",
+ type=str,
+ enum=FieldNote.Status.values,
+ required=False,
+ description="Filter to field notes in this lifecycle state (e.g. `pending` for unaddressed feedback).",
+ ),
+ OpenApiParameter(
+ "host",
+ type=str,
+ required=False,
+ description="Filter to field notes made on this hostname (e.g. `app.example.com`).",
+ ),
+ ]
+ )
+)
+class FieldNoteViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
+ """
+ Create, read, update, and resolve toolbar field notes — UI feedback a user
+ points at on their own site, surfaced to coding agents over MCP.
+ """
+
+ scope_object = "field_note"
+ # `.unscoped()` avoids the fail-closed manager raising at import (no team context yet);
+ # `safely_get_queryset` re-scopes every real query to the team.
+ queryset = FieldNote.objects.unscoped()
+ serializer_class = FieldNoteSerializer
+ lookup_field = "id"
+ permission_classes = [IsAuthenticated]
+
+ def safely_get_queryset(self, queryset: QuerySet) -> QuerySet:
+ queryset = queryset.filter(team_id=self.team_id)
+ field_note_status = self.request.query_params.get("field_note_status")
+ if field_note_status:
+ if field_note_status not in FieldNote.Status.values:
+ raise ValidationError({"field_note_status": f"Must be one of: {', '.join(FieldNote.Status.values)}"})
+ queryset = queryset.filter(field_note_status=field_note_status)
+ host = self.request.query_params.get("host")
+ if host:
+ queryset = queryset.filter(host=host)
+ return queryset.order_by("-created_at")
diff --git a/products/field_notes/backend/apps.py b/products/field_notes/backend/apps.py
new file mode 100644
index 000000000000..e6a35d7c1c3f
--- /dev/null
+++ b/products/field_notes/backend/apps.py
@@ -0,0 +1,7 @@
+from django.apps import AppConfig
+
+
+class FieldNotesConfig(AppConfig):
+ default_auto_field = "django.db.models.BigAutoField"
+ name = "products.field_notes.backend"
+ label = "field_notes"
diff --git a/products/field_notes/backend/migrations/0001_initial.py b/products/field_notes/backend/migrations/0001_initial.py
new file mode 100644
index 000000000000..7b1f1497159b
--- /dev/null
+++ b/products/field_notes/backend/migrations/0001_initial.py
@@ -0,0 +1,143 @@
+# Generated by Django 5.2.14 on 2026-06-09 23:01
+
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+import posthog.models.utils
+
+
+class Migration(migrations.Migration):
+ initial = True
+
+ dependencies = [
+ ("posthog", "1217_project_is_pending_deletion"),
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="FieldNote",
+ fields=[
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True, null=True)),
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.models.utils.UUIDT,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ (
+ "comment",
+ models.TextField(help_text="The note the user wrote about the element."),
+ ),
+ (
+ "field_note_status",
+ models.CharField(
+ choices=[
+ ("pending", "Pending"),
+ ("acknowledged", "Acknowledged"),
+ ("resolved", "Resolved"),
+ ("dismissed", "Dismissed"),
+ ],
+ default="pending",
+ help_text="Lifecycle of the field note as an agent works through it.",
+ max_length=20,
+ ),
+ ),
+ (
+ "resolution",
+ models.TextField(
+ blank=True,
+ help_text="Optional note left by the agent when acknowledging, resolving, or dismissing the field note.",
+ null=True,
+ ),
+ ),
+ (
+ "url",
+ models.TextField(help_text="Full URL of the page the field note was made on."),
+ ),
+ (
+ "host",
+ models.CharField(
+ help_text="Hostname of the page (e.g. app.example.com), used to scope field notes to a site.",
+ max_length=255,
+ ),
+ ),
+ (
+ "pathname",
+ models.TextField(blank=True, help_text="Path portion of the URL.", null=True),
+ ),
+ (
+ "selector",
+ models.TextField(help_text="CSS selector that locates the element on the page."),
+ ),
+ (
+ "element_text",
+ models.TextField(
+ blank=True,
+ help_text="Visible text of the element, if any.",
+ null=True,
+ ),
+ ),
+ (
+ "element_chain",
+ models.TextField(
+ blank=True,
+ help_text="Serialized autocapture-style element chain from the element up to the document root.",
+ null=True,
+ ),
+ ),
+ (
+ "element_context",
+ models.JSONField(
+ blank=True,
+ default=dict,
+ help_text="Structured element metadata (inferred selectors, attributes, component hints).",
+ ),
+ ),
+ (
+ "viewport",
+ models.JSONField(
+ blank=True,
+ help_text="Viewport size when the field note was made, as {width, height} in pixels.",
+ null=True,
+ ),
+ ),
+ (
+ "screenshot_url",
+ models.TextField(
+ blank=True,
+ help_text="URL of an uploaded screenshot captured with the field note.",
+ null=True,
+ ),
+ ),
+ (
+ "created_by",
+ models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="posthog.team"),
+ ),
+ ],
+ options={
+ "db_table": "posthog_field_note",
+ "indexes": [
+ models.Index(
+ fields=["team_id", "field_note_status"],
+ name="field_note_team_status_idx",
+ ),
+ models.Index(fields=["team_id", "host"], name="field_note_team_host_idx"),
+ ],
+ },
+ ),
+ ]
diff --git a/products/field_notes/backend/migrations/__init__.py b/products/field_notes/backend/migrations/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/field_notes/backend/migrations/max_migration.txt b/products/field_notes/backend/migrations/max_migration.txt
new file mode 100644
index 000000000000..cbab66dde92a
--- /dev/null
+++ b/products/field_notes/backend/migrations/max_migration.txt
@@ -0,0 +1 @@
+0001_initial
diff --git a/products/field_notes/backend/models.py b/products/field_notes/backend/models.py
new file mode 100644
index 000000000000..c18c576420af
--- /dev/null
+++ b/products/field_notes/backend/models.py
@@ -0,0 +1,76 @@
+from django.db import models
+
+from posthog.models.scoping.root_mixin import TeamScopedRootMixin
+from posthog.models.utils import CreatedMetaFields, UpdatedMetaFields, UUIDTModel
+
+
+class FieldNote(TeamScopedRootMixin, CreatedMetaFields, UpdatedMetaFields, UUIDTModel):
+ """
+ A UI field note captured from the PostHog toolbar on a user's own site.
+
+ The user points at an element, leaves a comment, and the toolbar records the
+ element selector plus page context. Field notes are surfaced over MCP so a
+ coding agent can pick them up and turn them into changes, then mark them resolved.
+ """
+
+ class Status(models.TextChoices):
+ PENDING = "pending", "Pending"
+ ACKNOWLEDGED = "acknowledged", "Acknowledged"
+ RESOLVED = "resolved", "Resolved"
+ DISMISSED = "dismissed", "Dismissed"
+
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)
+
+ comment = models.TextField(help_text="The note the user wrote about the element.")
+ # Field named `field_note_status` (not `status`) to avoid a drf-spectacular enum-name collision.
+ field_note_status = models.CharField(
+ max_length=20,
+ choices=Status.choices,
+ default=Status.PENDING,
+ help_text="Lifecycle of the field note as an agent works through it.",
+ )
+ resolution = models.TextField(
+ null=True,
+ blank=True,
+ help_text="Optional note left by the agent when acknowledging, resolving, or dismissing the field note.",
+ )
+
+ # Page context — where the field note was made.
+ url = models.TextField(help_text="Full URL of the page the field note was made on.")
+ host = models.CharField(
+ max_length=255,
+ help_text="Hostname of the page (e.g. app.example.com), used to scope field notes to a site.",
+ )
+ pathname = models.TextField(null=True, blank=True, help_text="Path portion of the URL.")
+
+ # Element context — what the user pointed at.
+ selector = models.TextField(help_text="CSS selector that locates the element on the page.")
+ element_text = models.TextField(null=True, blank=True, help_text="Visible text of the element, if any.")
+ element_chain = models.TextField(
+ null=True,
+ blank=True,
+ help_text="Serialized autocapture-style element chain from the element up to the document root.",
+ )
+ element_context = models.JSONField(
+ default=dict,
+ blank=True,
+ help_text="Structured element metadata (inferred selectors, attributes, component hints).",
+ )
+ viewport = models.JSONField(
+ null=True,
+ blank=True,
+ help_text="Viewport size when the field note was made, as {width, height} in pixels.",
+ )
+ screenshot_url = models.TextField(
+ null=True, blank=True, help_text="URL of an uploaded screenshot captured with the field note."
+ )
+
+ class Meta:
+ db_table = "posthog_field_note"
+ indexes = [
+ models.Index(fields=["team_id", "field_note_status"], name="field_note_team_status_idx"),
+ models.Index(fields=["team_id", "host"], name="field_note_team_host_idx"),
+ ]
+
+ def __str__(self) -> str:
+ return f"{self.id} @ {self.host}: {self.comment[:40]}"
diff --git a/products/field_notes/backend/routes.py b/products/field_notes/backend/routes.py
new file mode 100644
index 000000000000..58e86e3d1d03
--- /dev/null
+++ b/products/field_notes/backend/routes.py
@@ -0,0 +1,7 @@
+from posthog.api.routing import RouterRegistry
+
+from products.field_notes.backend.api import FieldNoteViewSet
+
+
+def register_routes(routers: RouterRegistry) -> None:
+ routers.projects.register(r"field_notes", FieldNoteViewSet, "environment_field_notes", ["team_id"])
diff --git a/products/field_notes/backend/test/__init__.py b/products/field_notes/backend/test/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/field_notes/backend/test/test_api.py b/products/field_notes/backend/test/test_api.py
new file mode 100644
index 000000000000..e145ecc564d6
--- /dev/null
+++ b/products/field_notes/backend/test/test_api.py
@@ -0,0 +1,104 @@
+from posthog.test.base import APIBaseTest
+
+from parameterized import parameterized
+from rest_framework import status
+
+from posthog.models.team.team import Team
+
+from products.field_notes.backend.models import FieldNote
+
+VALID_PAYLOAD = {
+ "comment": "This label needs less space",
+ "url": "https://app.example.com/dashboard/42",
+ "host": "app.example.com",
+ "pathname": "/dashboard/42",
+ "selector": ".header > .title",
+ "element_text": "Overview",
+ "element_context": {"inferred": {"text": "Overview"}},
+ "viewport": {"width": 1440, "height": 900},
+}
+
+
+class TestFieldNotesAPI(APIBaseTest):
+ def _create(self, **overrides) -> dict:
+ response = self.client.post(f"/api/projects/{self.team.id}/field_notes/", data={**VALID_PAYLOAD, **overrides})
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.json())
+ return response.json()
+
+ def test_create_sets_team_and_defaults(self):
+ created = self._create()
+ self.assertEqual(created["comment"], VALID_PAYLOAD["comment"])
+ self.assertEqual(created["host"], "app.example.com")
+ self.assertEqual(created["field_note_status"], "pending")
+ self.assertEqual(created["created_by"]["id"], self.user.pk)
+
+ field_note = FieldNote.objects.for_team(self.team.id).get(id=created["id"])
+ self.assertEqual(field_note.team_id, self.team.id)
+
+ def test_list_filters_by_status_and_host(self):
+ self._create()
+ resolved = self._create(comment="already done")
+ self.client.patch(
+ f"/api/projects/{self.team.id}/field_notes/{resolved['id']}/",
+ data={"field_note_status": "resolved"},
+ )
+ self._create(host="other.example.com")
+
+ pending = self.client.get(f"/api/projects/{self.team.id}/field_notes/?field_note_status=pending").json()[
+ "results"
+ ]
+ self.assertEqual(len(pending), 2)
+
+ by_host = self.client.get(f"/api/projects/{self.team.id}/field_notes/?host=other.example.com").json()["results"]
+ self.assertEqual(len(by_host), 1)
+ self.assertEqual(by_host[0]["host"], "other.example.com")
+
+ def test_resolve_with_note(self):
+ created = self._create()
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/field_notes/{created['id']}/",
+ data={"field_note_status": "resolved", "resolution": "Tightened the label spacing"},
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["field_note_status"], "resolved")
+ self.assertEqual(response.json()["resolution"], "Tightened the label spacing")
+
+ def test_create_ignores_status_and_resolution(self):
+ # A write-scoped toolbar token must not be able to forge a pre-resolved field_note.
+ created = self._create(field_note_status="resolved", resolution="forged")
+ self.assertEqual(created["field_note_status"], "pending")
+ self.assertIsNone(created["resolution"])
+
+ def test_list_rejects_invalid_status_filter(self):
+ self._create()
+ response = self.client.get(f"/api/projects/{self.team.id}/field_notes/?field_note_status=Resolved")
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+
+ @parameterized.expand(
+ [
+ ("comment", 5000),
+ ("url", 2048),
+ ("host", 255),
+ ("pathname", 2048),
+ ("selector", 4096),
+ ("element_text", 2048),
+ ("element_chain", 20000),
+ ("screenshot_url", 2048),
+ ]
+ )
+ def test_create_rejects_oversized_field(self, field: str, limit: int):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/field_notes/",
+ data={**VALID_PAYLOAD, field: "x" * (limit + 1)},
+ )
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.json())
+
+ def test_team_isolation(self):
+ created = self._create()
+ other_team = Team.objects.create(organization=self.organization, name="Other")
+
+ in_other = self.client.get(f"/api/projects/{other_team.id}/field_notes/").json()["results"]
+ self.assertEqual(in_other, [])
+
+ detail = self.client.get(f"/api/projects/{other_team.id}/field_notes/{created['id']}/")
+ self.assertEqual(detail.status_code, status.HTTP_404_NOT_FOUND)
diff --git a/products/field_notes/frontend/generated/api.schemas.ts b/products/field_notes/frontend/generated/api.schemas.ts
new file mode 100644
index 000000000000..9efbabea373e
--- /dev/null
+++ b/products/field_notes/frontend/generated/api.schemas.ts
@@ -0,0 +1,290 @@
+/**
+ * Auto-generated from the Django backend OpenAPI schema.
+ * To modify these types, update the Django serializers or views, then run:
+ * hogli build:openapi
+ * Questions or issues? #team-devex on Slack
+ *
+ * PostHog API - generated
+ * OpenAPI spec version: 1.0.0
+ */
+/**
+ * * `pending` - Pending
+ * * `acknowledged` - Acknowledged
+ * * `resolved` - Resolved
+ * * `dismissed` - Dismissed
+ */
+export type FieldNoteStatusEnumApi = (typeof FieldNoteStatusEnumApi)[keyof typeof FieldNoteStatusEnumApi]
+
+export const FieldNoteStatusEnumApi = {
+ Pending: 'pending',
+ Acknowledged: 'acknowledged',
+ Resolved: 'resolved',
+ Dismissed: 'dismissed',
+} as const
+
+/**
+ * * `engineering` - Engineering
+ * * `data` - Data
+ * * `product` - Product Management
+ * * `founder` - Founder
+ * * `leadership` - Leadership
+ * * `marketing` - Marketing
+ * * `sales` - Sales / Success
+ * * `other` - Other
+ */
+export type RoleAtOrganizationEnumApi = (typeof RoleAtOrganizationEnumApi)[keyof typeof RoleAtOrganizationEnumApi]
+
+export const RoleAtOrganizationEnumApi = {
+ Engineering: 'engineering',
+ Data: 'data',
+ Product: 'product',
+ Founder: 'founder',
+ Leadership: 'leadership',
+ Marketing: 'marketing',
+ Sales: 'sales',
+ Other: 'other',
+} as const
+
+export type BlankEnumApi = (typeof BlankEnumApi)[keyof typeof BlankEnumApi]
+
+export const BlankEnumApi = {
+ '': '',
+} as const
+
+/**
+ * @nullable
+ */
+export type UserBasicApiHedgehogConfig = { [key: string]: unknown } | null
+
+export interface UserBasicApi {
+ readonly id: number
+ readonly uuid: string
+ /**
+ * @maxLength 200
+ * @nullable
+ */
+ distinct_id?: string | null
+ /** @maxLength 150 */
+ first_name?: string
+ /** @maxLength 150 */
+ last_name?: string
+ /** @maxLength 254 */
+ email: string
+ /** @nullable */
+ is_email_verified?: boolean | null
+ /** @nullable */
+ readonly hedgehog_config: UserBasicApiHedgehogConfig
+ role_at_organization?: RoleAtOrganizationEnumApi | BlankEnumApi | null
+}
+
+/**
+ * Structured element metadata (inferred selectors, attributes, component hints).
+ */
+export type FieldNoteApiElementContext = { [key: string]: unknown }
+
+/**
+ * Viewport size when the field note was made, as {width, height}.
+ * @nullable
+ */
+export type FieldNoteApiViewport = {
+ /** Viewport width in pixels. */
+ width?: number
+ /** Viewport height in pixels. */
+ height?: number
+} | null
+
+export interface FieldNoteApi {
+ readonly id: string
+ /**
+ * The note the user wrote about the element.
+ * @maxLength 5000
+ */
+ comment: string
+ /** Lifecycle of the field note: pending, acknowledged, resolved, or dismissed. Ignored on create.
+ *
+ * * `pending` - Pending
+ * * `acknowledged` - Acknowledged
+ * * `resolved` - Resolved
+ * * `dismissed` - Dismissed */
+ field_note_status?: FieldNoteStatusEnumApi
+ /**
+ * Optional note left by the agent when acknowledging, resolving, or dismissing the field note.
+ * @nullable
+ */
+ resolution?: string | null
+ /**
+ * Full URL of the page the field note was made on.
+ * @maxLength 2048
+ */
+ url: string
+ /**
+ * Hostname of the page, used to scope field notes to a site.
+ * @maxLength 255
+ */
+ host: string
+ /**
+ * Path portion of the URL.
+ * @maxLength 2048
+ * @nullable
+ */
+ pathname?: string | null
+ /**
+ * CSS selector that locates the element on the page.
+ * @maxLength 4096
+ */
+ selector: string
+ /**
+ * Visible text of the element, if any.
+ * @maxLength 2048
+ * @nullable
+ */
+ element_text?: string | null
+ /**
+ * Serialized autocapture-style element chain from the element up to the document root.
+ * @maxLength 20000
+ * @nullable
+ */
+ element_chain?: string | null
+ /** Structured element metadata (inferred selectors, attributes, component hints). */
+ element_context?: FieldNoteApiElementContext
+ /**
+ * Viewport size when the field note was made, as {width, height}.
+ * @nullable
+ */
+ viewport?: FieldNoteApiViewport
+ /**
+ * URL of an uploaded screenshot captured with the field_note.
+ * @maxLength 2048
+ * @nullable
+ */
+ screenshot_url?: string | null
+ readonly created_at: string
+ /** @nullable */
+ readonly updated_at: string | null
+ readonly created_by: UserBasicApi
+}
+
+export interface PaginatedFieldNoteListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: FieldNoteApi[]
+}
+
+/**
+ * Structured element metadata (inferred selectors, attributes, component hints).
+ */
+export type PatchedFieldNoteApiElementContext = { [key: string]: unknown }
+
+/**
+ * Viewport size when the field note was made, as {width, height}.
+ * @nullable
+ */
+export type PatchedFieldNoteApiViewport = {
+ /** Viewport width in pixels. */
+ width?: number
+ /** Viewport height in pixels. */
+ height?: number
+} | null
+
+export interface PatchedFieldNoteApi {
+ readonly id?: string
+ /**
+ * The note the user wrote about the element.
+ * @maxLength 5000
+ */
+ comment?: string
+ /** Lifecycle of the field note: pending, acknowledged, resolved, or dismissed. Ignored on create.
+ *
+ * * `pending` - Pending
+ * * `acknowledged` - Acknowledged
+ * * `resolved` - Resolved
+ * * `dismissed` - Dismissed */
+ field_note_status?: FieldNoteStatusEnumApi
+ /**
+ * Optional note left by the agent when acknowledging, resolving, or dismissing the field note.
+ * @nullable
+ */
+ resolution?: string | null
+ /**
+ * Full URL of the page the field note was made on.
+ * @maxLength 2048
+ */
+ url?: string
+ /**
+ * Hostname of the page, used to scope field notes to a site.
+ * @maxLength 255
+ */
+ host?: string
+ /**
+ * Path portion of the URL.
+ * @maxLength 2048
+ * @nullable
+ */
+ pathname?: string | null
+ /**
+ * CSS selector that locates the element on the page.
+ * @maxLength 4096
+ */
+ selector?: string
+ /**
+ * Visible text of the element, if any.
+ * @maxLength 2048
+ * @nullable
+ */
+ element_text?: string | null
+ /**
+ * Serialized autocapture-style element chain from the element up to the document root.
+ * @maxLength 20000
+ * @nullable
+ */
+ element_chain?: string | null
+ /** Structured element metadata (inferred selectors, attributes, component hints). */
+ element_context?: PatchedFieldNoteApiElementContext
+ /**
+ * Viewport size when the field note was made, as {width, height}.
+ * @nullable
+ */
+ viewport?: PatchedFieldNoteApiViewport
+ /**
+ * URL of an uploaded screenshot captured with the field_note.
+ * @maxLength 2048
+ * @nullable
+ */
+ screenshot_url?: string | null
+ readonly created_at?: string
+ /** @nullable */
+ readonly updated_at?: string | null
+ readonly created_by?: UserBasicApi
+}
+
+export type FieldNotesListParams = {
+ /**
+ * Filter to field notes in this lifecycle state (e.g. `pending` for unaddressed feedback).
+ */
+ field_note_status?: FieldNotesListFieldNoteStatus
+ /**
+ * Filter to field notes made on this hostname (e.g. `app.example.com`).
+ */
+ host?: string
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
+}
+
+export type FieldNotesListFieldNoteStatus =
+ (typeof FieldNotesListFieldNoteStatus)[keyof typeof FieldNotesListFieldNoteStatus]
+
+export const FieldNotesListFieldNoteStatus = {
+ Acknowledged: 'acknowledged',
+ Dismissed: 'dismissed',
+ Pending: 'pending',
+ Resolved: 'resolved',
+} as const
diff --git a/products/field_notes/frontend/generated/api.ts b/products/field_notes/frontend/generated/api.ts
new file mode 100644
index 000000000000..348e258fbd42
--- /dev/null
+++ b/products/field_notes/frontend/generated/api.ts
@@ -0,0 +1,158 @@
+import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
+/**
+ * Auto-generated from the Django backend OpenAPI schema.
+ * To modify these types, update the Django serializers or views, then run:
+ * hogli build:openapi
+ * Questions or issues? #team-devex on Slack
+ *
+ * PostHog API - generated
+ * OpenAPI spec version: 1.0.0
+ */
+import type { FieldNoteApi, FieldNotesListParams, PaginatedFieldNoteListApi, PatchedFieldNoteApi } from './api.schemas'
+
+// https://stackoverflow.com/questions/49579094/typescript-conditional-types-filter-out-readonly-properties-pick-only-requir/49579497#49579497
+type IfEquals<X, Y, A = X, B = never> = (<T>() => T extends X ? 1 : 2) extends <T>() => T extends Y ? 1 : 2 ? A : B
+
+type WritableKeys<T> = {
+ [P in keyof T]-?: IfEquals<{ [Q in P]: T[P] }, { -readonly [Q in P]: T[P] }, P>
+}[keyof T]
+
+type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never
+type DistributeReadOnlyOverUnions<T> = T extends any ? NonReadonly<T> : never
+
+type Writable<T> = Pick<T, WritableKeys<T>>
+type NonReadonly<T> = [T] extends [UnionToIntersection<T>]
+ ? {
+ [P in keyof Writable<T>]: T[P] extends object ? NonReadonly<NonNullable<T[P]>> : T[P]
+ }
+ : DistributeReadOnlyOverUnions<T>
+
+export const getFieldNotesListUrl = (projectId: string, params?: FieldNotesListParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/field_notes/?${stringifiedParams}`
+ : `/api/projects/${projectId}/field_notes/`
+}
+
+/**
+ * Create, read, update, and resolve toolbar field notes — UI feedback a user
+ * points at on their own site, surfaced to coding agents over MCP.
+ */
+export const fieldNotesList = async (
+ projectId: string,
+ params?: FieldNotesListParams,
+ options?: RequestInit
+): Promise<PaginatedFieldNoteListApi> => {
+ return apiMutator<PaginatedFieldNoteListApi>(getFieldNotesListUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getFieldNotesCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/field_notes/`
+}
+
+/**
+ * Create, read, update, and resolve toolbar field notes — UI feedback a user
+ * points at on their own site, surfaced to coding agents over MCP.
+ */
+export const fieldNotesCreate = async (
+ projectId: string,
+ fieldNoteApi: NonReadonly<FieldNoteApi>,
+ options?: RequestInit
+): Promise<FieldNoteApi> => {
+ return apiMutator<FieldNoteApi>(getFieldNotesCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(fieldNoteApi),
+ })
+}
+
+export const getFieldNotesRetrieveUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/field_notes/${id}/`
+}
+
+/**
+ * Create, read, update, and resolve toolbar field notes — UI feedback a user
+ * points at on their own site, surfaced to coding agents over MCP.
+ */
+export const fieldNotesRetrieve = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<FieldNoteApi> => {
+ return apiMutator<FieldNoteApi>(getFieldNotesRetrieveUrl(projectId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getFieldNotesUpdateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/field_notes/${id}/`
+}
+
+/**
+ * Create, read, update, and resolve toolbar field notes — UI feedback a user
+ * points at on their own site, surfaced to coding agents over MCP.
+ */
+export const fieldNotesUpdate = async (
+ projectId: string,
+ id: string,
+ fieldNoteApi: NonReadonly<FieldNoteApi>,
+ options?: RequestInit
+): Promise<FieldNoteApi> => {
+ return apiMutator<FieldNoteApi>(getFieldNotesUpdateUrl(projectId, id), {
+ ...options,
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(fieldNoteApi),
+ })
+}
+
+export const getFieldNotesPartialUpdateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/field_notes/${id}/`
+}
+
+/**
+ * Create, read, update, and resolve toolbar field notes — UI feedback a user
+ * points at on their own site, surfaced to coding agents over MCP.
+ */
+export const fieldNotesPartialUpdate = async (
+ projectId: string,
+ id: string,
+ patchedFieldNoteApi?: NonReadonly<PatchedFieldNoteApi>,
+ options?: RequestInit
+): Promise<FieldNoteApi> => {
+ return apiMutator<FieldNoteApi>(getFieldNotesPartialUpdateUrl(projectId, id), {
+ ...options,
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(patchedFieldNoteApi),
+ })
+}
+
+export const getFieldNotesDestroyUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/field_notes/${id}/`
+}
+
+/**
+ * Create, read, update, and resolve toolbar field notes — UI feedback a user
+ * points at on their own site, surfaced to coding agents over MCP.
+ */
+export const fieldNotesDestroy = async (projectId: string, id: string, options?: RequestInit): Promise<void> => {
+ return apiMutator<void>(getFieldNotesDestroyUrl(projectId, id), {
+ ...options,
+ method: 'DELETE',
+ })
+}
diff --git a/products/field_notes/frontend/generated/api.zod.ts b/products/field_notes/frontend/generated/api.zod.ts
new file mode 100644
index 000000000000..1fb64df68f31
--- /dev/null
+++ b/products/field_notes/frontend/generated/api.zod.ts
@@ -0,0 +1,239 @@
+/**
+ * Auto-generated Zod validation schemas from the Django backend OpenAPI schema.
+ * To modify these schemas, update the Django serializers or views, then run:
+ * hogli build:openapi
+ * Questions or issues? #team-devex on Slack
+ *
+ * PostHog API - generated
+ * OpenAPI spec version: 1.0.0
+ */
+import * as zod from 'zod'
+
+/**
+ * Create, read, update, and resolve toolbar field notes — UI feedback a user
+ * points at on their own site, surfaced to coding agents over MCP.
+ */
+export const fieldNotesCreateBodyCommentMax = 5000
+
+export const fieldNotesCreateBodyUrlMax = 2048
+
+export const fieldNotesCreateBodyHostMax = 255
+
+export const fieldNotesCreateBodyPathnameMax = 2048
+
+export const fieldNotesCreateBodySelectorMax = 4096
+
+export const fieldNotesCreateBodyElementTextMax = 2048
+
+export const fieldNotesCreateBodyElementChainMax = 20000
+
+export const fieldNotesCreateBodyScreenshotUrlMax = 2048
+
+export const FieldNotesCreateBody = /* @__PURE__ */ zod.object({
+ comment: zod.string().max(fieldNotesCreateBodyCommentMax).describe('The note the user wrote about the element.'),
+ field_note_status: zod
+ .enum(['pending', 'acknowledged', 'resolved', 'dismissed'])
+ .describe(
+ '\* `pending` - Pending\n\* `acknowledged` - Acknowledged\n\* `resolved` - Resolved\n\* `dismissed` - Dismissed'
+ )
+ .optional()
+ .describe(
+ 'Lifecycle of the field note: pending, acknowledged, resolved, or dismissed. Ignored on create.\n\n\* `pending` - Pending\n\* `acknowledged` - Acknowledged\n\* `resolved` - Resolved\n\* `dismissed` - Dismissed'
+ ),
+ resolution: zod
+ .string()
+ .nullish()
+ .describe('Optional note left by the agent when acknowledging, resolving, or dismissing the field note.'),
+ url: zod.string().max(fieldNotesCreateBodyUrlMax).describe('Full URL of the page the field note was made on.'),
+ host: zod
+ .string()
+ .max(fieldNotesCreateBodyHostMax)
+ .describe('Hostname of the page, used to scope field notes to a site.'),
+ pathname: zod.string().max(fieldNotesCreateBodyPathnameMax).nullish().describe('Path portion of the URL.'),
+ selector: zod
+ .string()
+ .max(fieldNotesCreateBodySelectorMax)
+ .describe('CSS selector that locates the element on the page.'),
+ element_text: zod
+ .string()
+ .max(fieldNotesCreateBodyElementTextMax)
+ .nullish()
+ .describe('Visible text of the element, if any.'),
+ element_chain: zod
+ .string()
+ .max(fieldNotesCreateBodyElementChainMax)
+ .nullish()
+ .describe('Serialized autocapture-style element chain from the element up to the document root.'),
+ element_context: zod
+ .record(zod.string(), zod.unknown())
+ .optional()
+ .describe('Structured element metadata (inferred selectors, attributes, component hints).'),
+ viewport: zod
+ .object({
+ width: zod.number().optional().describe('Viewport width in pixels.'),
+ height: zod.number().optional().describe('Viewport height in pixels.'),
+ })
+ .nullish()
+ .describe('Viewport size when the field note was made, as {width, height}.'),
+ screenshot_url: zod
+ .string()
+ .max(fieldNotesCreateBodyScreenshotUrlMax)
+ .nullish()
+ .describe('URL of an uploaded screenshot captured with the field_note.'),
+})
+
+/**
+ * Create, read, update, and resolve toolbar field notes — UI feedback a user
+ * points at on their own site, surfaced to coding agents over MCP.
+ */
+export const fieldNotesUpdateBodyCommentMax = 5000
+
+export const fieldNotesUpdateBodyUrlMax = 2048
+
+export const fieldNotesUpdateBodyHostMax = 255
+
+export const fieldNotesUpdateBodyPathnameMax = 2048
+
+export const fieldNotesUpdateBodySelectorMax = 4096
+
+export const fieldNotesUpdateBodyElementTextMax = 2048
+
+export const fieldNotesUpdateBodyElementChainMax = 20000
+
+export const fieldNotesUpdateBodyScreenshotUrlMax = 2048
+
+export const FieldNotesUpdateBody = /* @__PURE__ */ zod.object({
+ comment: zod.string().max(fieldNotesUpdateBodyCommentMax).describe('The note the user wrote about the element.'),
+ field_note_status: zod
+ .enum(['pending', 'acknowledged', 'resolved', 'dismissed'])
+ .describe(
+ '\* `pending` - Pending\n\* `acknowledged` - Acknowledged\n\* `resolved` - Resolved\n\* `dismissed` - Dismissed'
+ )
+ .optional()
+ .describe(
+ 'Lifecycle of the field note: pending, acknowledged, resolved, or dismissed. Ignored on create.\n\n\* `pending` - Pending\n\* `acknowledged` - Acknowledged\n\* `resolved` - Resolved\n\* `dismissed` - Dismissed'
+ ),
+ resolution: zod
+ .string()
+ .nullish()
+ .describe('Optional note left by the agent when acknowledging, resolving, or dismissing the field note.'),
+ url: zod.string().max(fieldNotesUpdateBodyUrlMax).describe('Full URL of the page the field note was made on.'),
+ host: zod
+ .string()
+ .max(fieldNotesUpdateBodyHostMax)
+ .describe('Hostname of the page, used to scope field notes to a site.'),
+ pathname: zod.string().max(fieldNotesUpdateBodyPathnameMax).nullish().describe('Path portion of the URL.'),
+ selector: zod
+ .string()
+ .max(fieldNotesUpdateBodySelectorMax)
+ .describe('CSS selector that locates the element on the page.'),
+ element_text: zod
+ .string()
+ .max(fieldNotesUpdateBodyElementTextMax)
+ .nullish()
+ .describe('Visible text of the element, if any.'),
+ element_chain: zod
+ .string()
+ .max(fieldNotesUpdateBodyElementChainMax)
+ .nullish()
+ .describe('Serialized autocapture-style element chain from the element up to the document root.'),
+ element_context: zod
+ .record(zod.string(), zod.unknown())
+ .optional()
+ .describe('Structured element metadata (inferred selectors, attributes, component hints).'),
+ viewport: zod
+ .object({
+ width: zod.number().optional().describe('Viewport width in pixels.'),
+ height: zod.number().optional().describe('Viewport height in pixels.'),
+ })
+ .nullish()
+ .describe('Viewport size when the field note was made, as {width, height}.'),
+ screenshot_url: zod
+ .string()
+ .max(fieldNotesUpdateBodyScreenshotUrlMax)
+ .nullish()
+ .describe('URL of an uploaded screenshot captured with the field_note.'),
+})
+
+/**
+ * Create, read, update, and resolve toolbar field notes — UI feedback a user
+ * points at on their own site, surfaced to coding agents over MCP.
+ */
+export const fieldNotesPartialUpdateBodyCommentMax = 5000
+
+export const fieldNotesPartialUpdateBodyUrlMax = 2048
+
+export const fieldNotesPartialUpdateBodyHostMax = 255
+
+export const fieldNotesPartialUpdateBodyPathnameMax = 2048
+
+export const fieldNotesPartialUpdateBodySelectorMax = 4096
+
+export const fieldNotesPartialUpdateBodyElementTextMax = 2048
+
+export const fieldNotesPartialUpdateBodyElementChainMax = 20000
+
+export const fieldNotesPartialUpdateBodyScreenshotUrlMax = 2048
+
+export const FieldNotesPartialUpdateBody = /* @__PURE__ */ zod.object({
+ comment: zod
+ .string()
+ .max(fieldNotesPartialUpdateBodyCommentMax)
+ .optional()
+ .describe('The note the user wrote about the element.'),
+ field_note_status: zod
+ .enum(['pending', 'acknowledged', 'resolved', 'dismissed'])
+ .describe(
+ '\* `pending` - Pending\n\* `acknowledged` - Acknowledged\n\* `resolved` - Resolved\n\* `dismissed` - Dismissed'
+ )
+ .optional()
+ .describe(
+ 'Lifecycle of the field note: pending, acknowledged, resolved, or dismissed. Ignored on create.\n\n\* `pending` - Pending\n\* `acknowledged` - Acknowledged\n\* `resolved` - Resolved\n\* `dismissed` - Dismissed'
+ ),
+ resolution: zod
+ .string()
+ .nullish()
+ .describe('Optional note left by the agent when acknowledging, resolving, or dismissing the field note.'),
+ url: zod
+ .string()
+ .max(fieldNotesPartialUpdateBodyUrlMax)
+ .optional()
+ .describe('Full URL of the page the field note was made on.'),
+ host: zod
+ .string()
+ .max(fieldNotesPartialUpdateBodyHostMax)
+ .optional()
+ .describe('Hostname of the page, used to scope field notes to a site.'),
+ pathname: zod.string().max(fieldNotesPartialUpdateBodyPathnameMax).nullish().describe('Path portion of the URL.'),
+ selector: zod
+ .string()
+ .max(fieldNotesPartialUpdateBodySelectorMax)
+ .optional()
+ .describe('CSS selector that locates the element on the page.'),
+ element_text: zod
+ .string()
+ .max(fieldNotesPartialUpdateBodyElementTextMax)
+ .nullish()
+ .describe('Visible text of the element, if any.'),
+ element_chain: zod
+ .string()
+ .max(fieldNotesPartialUpdateBodyElementChainMax)
+ .nullish()
+ .describe('Serialized autocapture-style element chain from the element up to the document root.'),
+ element_context: zod
+ .record(zod.string(), zod.unknown())
+ .optional()
+ .describe('Structured element metadata (inferred selectors, attributes, component hints).'),
+ viewport: zod
+ .object({
+ width: zod.number().optional().describe('Viewport width in pixels.'),
+ height: zod.number().optional().describe('Viewport height in pixels.'),
+ })
+ .nullish()
+ .describe('Viewport size when the field note was made, as {width, height}.'),
+ screenshot_url: zod
+ .string()
+ .max(fieldNotesPartialUpdateBodyScreenshotUrlMax)
+ .nullish()
+ .describe('URL of an uploaded screenshot captured with the field_note.'),
+})
diff --git a/products/field_notes/mcp/tools.yaml b/products/field_notes/mcp/tools.yaml
new file mode 100644
index 000000000000..286b1e58f432
--- /dev/null
+++ b/products/field_notes/mcp/tools.yaml
@@ -0,0 +1,83 @@
+# MCP tool definition — tool entries are scaffolded from the OpenAPI schema.
+# The tool list and operation IDs are kept in sync automatically:
+# pnpm --filter=@posthog/mcp run scaffold-yaml -- --sync-all
+#
+# To enable a tool, set enabled: true and add required scopes + annotations.
+# All other fields (title, description, enrich_url, etc.) are yours to configure.
+category: Field notes
+feature: field_notes
+url_prefix: /field_notes
+ui_apps: {}
+tools:
+ field-notes-create:
+ operation: field_notes_create
+ enabled: false
+ field-notes-destroy:
+ operation: field_notes_destroy
+ enabled: false
+ field-notes-get:
+ operation: field_notes_retrieve
+ enabled: true
+ scopes:
+ - field_note:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ enrich_url: '{id}'
+ title: Get field note
+ description: >
+ Get a single field note by id, including the full element context (selector, element chain, inferred
+ selectors, attributes) needed to locate the element in code.
+ feature_flag: field-notes
+ field-notes-list:
+ operation: field_notes_list
+ enabled: true
+ scopes:
+ - field_note:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ enrich_url: '{id}'
+ list: true
+ title: List field notes
+ description: >
+ List UI field notes a user made with the PostHog toolbar on their own site. Each field note is feedback
+ pointed at a specific page element — comment, CSS selector, page URL, host, and optional screenshot. Filter
+ by `field_note_status` (pending, acknowledged, resolved, dismissed) to find unaddressed feedback, or by
+ `host` to scope to one site. Use this to pick up pending design/UX feedback to act on.
+ feature_flag: field-notes
+ response:
+ include:
+ - id
+ - comment
+ - field_note_status
+ - resolution
+ - url
+ - host
+ - pathname
+ - selector
+ - element_text
+ - screenshot_url
+ - created_at
+ - created_by
+ field-notes-partial-update:
+ operation: field_notes_partial_update
+ enabled: true
+ scopes:
+ - field_note:write
+ annotations:
+ readOnly: false
+ destructive: false
+ idempotent: true
+ enrich_url: '{id}'
+ title: Update field note
+ description: >
+ Update a field note after acting on it — set `field_note_status` to `acknowledged`, `resolved`, or
+ `dismissed`, and optionally add a `resolution` note describing what changed. Send only the fields you want
+ to change.
+ feature_flag: field-notes
+ field-notes-update:
+ operation: field_notes_update
+ enabled: false
diff --git a/products/field_notes/package.json b/products/field_notes/package.json
new file mode 100644
index 000000000000..e2e1ecee2dfe
--- /dev/null
+++ b/products/field_notes/package.json
@@ -0,0 +1,6 @@
+{
+ "name": "@posthog/products-field-notes",
+ "scripts": {
+ "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/ -v --tb=short"
+ }
+}
diff --git a/products/field_notes/product.yaml b/products/field_notes/product.yaml
new file mode 100644
index 000000000000..ba7b528d6315
--- /dev/null
+++ b/products/field_notes/product.yaml
@@ -0,0 +1,3 @@
+name: Field notes
+owners:
+ - team-surveys
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 16dcce019f8d..44b09bf98a88 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -2655,6 +2655,51 @@
"readOnlyHint": true
}
},
+ "field-notes-get": {
+ "description": "Get a single field note by id, including the full element context (selector, element chain, inferred selectors, attributes) needed to locate the element in code.",
+ "category": "Field notes",
+ "feature": "field_notes",
+ "summary": "Get field note",
+ "title": "Get field note",
+ "required_scopes": ["field_note:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "field-notes"
+ },
+ "field-notes-list": {
+ "description": "List UI field notes a user made with the PostHog toolbar on their own site. Each field note is feedback pointed at a specific page element — comment, CSS selector, page URL, host, and optional screenshot. Filter by `field_note_status` (pending, acknowledged, resolved, dismissed) to find unaddressed feedback, or by `host` to scope to one site. Use this to pick up pending design/UX feedback to act on.",
+ "category": "Field notes",
+ "feature": "field_notes",
+ "summary": "List field notes",
+ "title": "List field notes",
+ "required_scopes": ["field_note:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "field-notes"
+ },
+ "field-notes-partial-update": {
+ "description": "Update a field note after acting on it — set `field_note_status` to `acknowledged`, `resolved`, or `dismissed`, and optionally add a `resolution` note describing what changed. Send only the fields you want to change.",
+ "category": "Field notes",
+ "feature": "field_notes",
+ "summary": "Update field note",
+ "title": "Update field note",
+ "required_scopes": ["field_note:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "field-notes"
+ },
"file-download-batch-exports-cancel-create": {
"description": "Cancel a running or starting on-demand file download export. When the status is not Starting or Running calling this will fail. Returns the status of the export after cancelling, which is always Cancelled.",
"category": "Data pipelines",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index d565d725e05b..e06bf798db54 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -2881,6 +2881,51 @@
"readOnlyHint": true
}
},
+ "field-notes-get": {
+ "description": "Get a single field note by id, including the full element context (selector, element chain, inferred selectors, attributes) needed to locate the element in code.",
+ "category": "Field notes",
+ "feature": "field_notes",
+ "summary": "Get field note",
+ "title": "Get field note",
+ "required_scopes": ["field_note:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "field-notes"
+ },
+ "field-notes-list": {
+ "description": "List UI field notes a user made with the PostHog toolbar on their own site. Each field note is feedback pointed at a specific page element — comment, CSS selector, page URL, host, and optional screenshot. Filter by `field_note_status` (pending, acknowledged, resolved, dismissed) to find unaddressed feedback, or by `host` to scope to one site. Use this to pick up pending design/UX feedback to act on.",
+ "category": "Field notes",
+ "feature": "field_notes",
+ "summary": "List field notes",
+ "title": "List field notes",
+ "required_scopes": ["field_note:read"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": true
+ },
+ "feature_flag": "field-notes"
+ },
+ "field-notes-partial-update": {
+ "description": "Update a field note after acting on it — set `field_note_status` to `acknowledged`, `resolved`, or `dismissed`, and optionally add a `resolution` note describing what changed. Send only the fields you want to change.",
+ "category": "Field notes",
+ "feature": "field_notes",
+ "summary": "Update field note",
+ "title": "Update field note",
+ "required_scopes": ["field_note:write"],
+ "annotations": {
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true,
+ "readOnlyHint": false
+ },
+ "feature_flag": "field-notes"
+ },
"file-download-batch-exports-cancel-create": {
"description": "Cancel a running or starting on-demand file download export. When the status is not Starting or Running calling this will fail. Returns the status of the export after cancelling, which is always Cancelled.",
"category": "Data pipelines",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index bbb557afdec1..7e709b1258cf 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -18926,6 +18926,109 @@ export namespace Schemas {
readonly modified_by: number | null;
}
+ /**
+ * Structured element metadata (inferred selectors, attributes, component hints).
+ */
+ export type FieldNoteElementContext = { [key: string]: unknown };
+
+ /**
+ * Viewport size when the field note was made, as {width, height}.
+ * @nullable
+ */
+ export type FieldNoteViewport = {
+ /** Viewport width in pixels. */
+ width?: number;
+ /** Viewport height in pixels. */
+ height?: number;
+ } | null;
+
+ /**
+ * * `pending` - Pending
+ * * `acknowledged` - Acknowledged
+ * * `resolved` - Resolved
+ * * `dismissed` - Dismissed
+ */
+ export type FieldNoteStatusEnum = typeof FieldNoteStatusEnum[keyof typeof FieldNoteStatusEnum];
+
+
+ export const FieldNoteStatusEnum = {
+ Pending: 'pending',
+ Acknowledged: 'acknowledged',
+ Resolved: 'resolved',
+ Dismissed: 'dismissed',
+ } as const;
+
+ export interface FieldNote {
+ readonly id: string;
+ /**
+ * The note the user wrote about the element.
+ * @maxLength 5000
+ */
+ comment: string;
+ /** Lifecycle of the field note: pending, acknowledged, resolved, or dismissed. Ignored on create.
+ *
+ * * `pending` - Pending
+ * * `acknowledged` - Acknowledged
+ * * `resolved` - Resolved
+ * * `dismissed` - Dismissed */
+ field_note_status?: FieldNoteStatusEnum;
+ /**
+ * Optional note left by the agent when acknowledging, resolving, or dismissing the field note.
+ * @nullable
+ */
+ resolution?: string | null;
+ /**
+ * Full URL of the page the field note was made on.
+ * @maxLength 2048
+ */
+ url: string;
+ /**
+ * Hostname of the page, used to scope field notes to a site.
+ * @maxLength 255
+ */
+ host: string;
+ /**
+ * Path portion of the URL.
+ * @maxLength 2048
+ * @nullable
+ */
+ pathname?: string | null;
+ /**
+ * CSS selector that locates the element on the page.
+ * @maxLength 4096
+ */
+ selector: string;
+ /**
+ * Visible text of the element, if any.
+ * @maxLength 2048
+ * @nullable
+ */
+ element_text?: string | null;
+ /**
+ * Serialized autocapture-style element chain from the element up to the document root.
+ * @maxLength 20000
+ * @nullable
+ */
+ element_chain?: string | null;
+ /** Structured element metadata (inferred selectors, attributes, component hints). */
+ element_context?: FieldNoteElementContext;
+ /**
+ * Viewport size when the field note was made, as {width, height}.
+ * @nullable
+ */
+ viewport?: FieldNoteViewport;
+ /**
+ * URL of an uploaded screenshot captured with the field_note.
+ * @maxLength 2048
+ * @nullable
+ */
+ screenshot_url?: string | null;
+ readonly created_at: string;
+ /** @nullable */
+ readonly updated_at: string | null;
+ readonly created_by: UserBasic;
+ }
+
/**
* * `events` - events
* * `persons` - persons
@@ -25271,6 +25374,15 @@ export namespace Schemas {
results: FeatureFlag[];
}
+ export interface PaginatedFieldNoteList {
+ count: number;
+ /** @nullable */
+ next?: string | null;
+ /** @nullable */
+ previous?: string | null;
+ results: FieldNote[];
+ }
+
export interface PaginatedFileSystemList {
count: number;
/** @nullable */
@@ -30584,6 +30696,93 @@ export namespace Schemas {
is_remote_configuration?: boolean | null;
}
+ /**
+ * Structured element metadata (inferred selectors, attributes, component hints).
+ */
+ export type PatchedFieldNoteElementContext = { [key: string]: unknown };
+
+ /**
+ * Viewport size when the field note was made, as {width, height}.
+ * @nullable
+ */
+ export type PatchedFieldNoteViewport = {
+ /** Viewport width in pixels. */
+ width?: number;
+ /** Viewport height in pixels. */
+ height?: number;
+ } | null;
+
+ export interface PatchedFieldNote {
+ readonly id?: string;
+ /**
+ * The note the user wrote about the element.
+ * @maxLength 5000
+ */
+ comment?: string;
+ /** Lifecycle of the field note: pending, acknowledged, resolved, or dismissed. Ignored on create.
+ *
+ * * `pending` - Pending
+ * * `acknowledged` - Acknowledged
+ * * `resolved` - Resolved
+ * * `dismissed` - Dismissed */
+ field_note_status?: FieldNoteStatusEnum;
+ /**
+ * Optional note left by the agent when acknowledging, resolving, or dismissing the field note.
+ * @nullable
+ */
+ resolution?: string | null;
+ /**
+ * Full URL of the page the field note was made on.
+ * @maxLength 2048
+ */
+ url?: string;
+ /**
+ * Hostname of the page, used to scope field notes to a site.
+ * @maxLength 255
+ */
+ host?: string;
+ /**
+ * Path portion of the URL.
+ * @maxLength 2048
+ * @nullable
+ */
+ pathname?: string | null;
+ /**
+ * CSS selector that locates the element on the page.
+ * @maxLength 4096
+ */
+ selector?: string;
+ /**
+ * Visible text of the element, if any.
+ * @maxLength 2048
+ * @nullable
+ */
+ element_text?: string | null;
+ /**
+ * Serialized autocapture-style element chain from the element up to the document root.
+ * @maxLength 20000
+ * @nullable
+ */
+ element_chain?: string | null;
+ /** Structured element metadata (inferred selectors, attributes, component hints). */
+ element_context?: PatchedFieldNoteElementContext;
+ /**
+ * Viewport size when the field note was made, as {width, height}.
+ * @nullable
+ */
+ viewport?: PatchedFieldNoteViewport;
+ /**
+ * URL of an uploaded screenshot captured with the field_note.
+ * @maxLength 2048
+ * @nullable
+ */
+ screenshot_url?: string | null;
+ readonly created_at?: string;
+ /** @nullable */
+ readonly updated_at?: string | null;
+ readonly created_by?: UserBasic;
+ }
+
export interface PatchedFileSystem {
readonly id?: string;
path?: string;
@@ -50176,6 +50375,35 @@ export namespace Schemas {
groups?: string;
};
+ export type FieldNotesListParams = {
+ /**
+ * Filter to field notes in this lifecycle state (e.g. `pending` for unaddressed feedback).
+ */
+ field_note_status?: FieldNotesListFieldNoteStatus;
+ /**
+ * Filter to field notes made on this hostname (e.g. `app.example.com`).
+ */
+ host?: string;
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number;
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number;
+ };
+
+ export type FieldNotesListFieldNoteStatus = typeof FieldNotesListFieldNoteStatus[keyof typeof FieldNotesListFieldNoteStatus];
+
+
+ export const FieldNotesListFieldNoteStatus = {
+ Acknowledged: 'acknowledged',
+ Dismissed: 'dismissed',
+ Pending: 'pending',
+ Resolved: 'resolved',
+ } as const;
+
export type FileDownloadBatchExportsListParams = {
/**
* Number of results to return per page.
diff --git a/services/mcp/src/generated/field_notes/api.ts b/services/mcp/src/generated/field_notes/api.ts
new file mode 100644
index 000000000000..21c11f873586
--- /dev/null
+++ b/services/mcp/src/generated/field_notes/api.ts
@@ -0,0 +1,136 @@
+/**
+ * Auto-generated from the Django backend OpenAPI schema.
+ * MCP service uses these Zod schemas for generated tool handlers.
+ * To regenerate: hogli build:openapi
+ *
+ * PostHog API - MCP 3 enabled ops
+ * OpenAPI spec version: 1.0.0
+ */
+import * as zod from 'zod'
+
+/**
+ * Create, read, update, and resolve toolbar field notes — UI feedback a user
+ * points at on their own site, surfaced to coding agents over MCP.
+ */
+export const FieldNotesListParams = /* @__PURE__ */ zod.object({
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."
+ ),
+})
+
+export const FieldNotesListQueryParams = /* @__PURE__ */ zod.object({
+ field_note_status: zod
+ .enum(['acknowledged', 'dismissed', 'pending', 'resolved'])
+ .optional()
+ .describe('Filter to field notes in this lifecycle state (e.g. `pending` for unaddressed feedback).'),
+ host: zod.string().optional().describe('Filter to field notes made on this hostname (e.g. `app.example.com`).'),
+ limit: zod.number().optional().describe('Number of results to return per page.'),
+ offset: zod.number().optional().describe('The initial index from which to return the results.'),
+})
+
+/**
+ * Create, read, update, and resolve toolbar field notes — UI feedback a user
+ * points at on their own site, surfaced to coding agents over MCP.
+ */
+export const FieldNotesRetrieveParams = /* @__PURE__ */ zod.object({
+ id: zod.string().describe('A UUID string identifying this field note.'),
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."
+ ),
+})
+
+/**
+ * Create, read, update, and resolve toolbar field notes — UI feedback a user
+ * points at on their own site, surfaced to coding agents over MCP.
+ */
+export const FieldNotesPartialUpdateParams = /* @__PURE__ */ zod.object({
+ id: zod.string().describe('A UUID string identifying this field note.'),
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."
+ ),
+})
+
+export const fieldNotesPartialUpdateBodyCommentMax = 5000
+
+export const fieldNotesPartialUpdateBodyUrlMax = 2048
+
+export const fieldNotesPartialUpdateBodyHostMax = 255
+
+export const fieldNotesPartialUpdateBodyPathnameMax = 2048
+
+export const fieldNotesPartialUpdateBodySelectorMax = 4096
+
+export const fieldNotesPartialUpdateBodyElementTextMax = 2048
+
+export const fieldNotesPartialUpdateBodyElementChainMax = 20000
+
+export const fieldNotesPartialUpdateBodyScreenshotUrlMax = 2048
+
+export const FieldNotesPartialUpdateBody = /* @__PURE__ */ zod.object({
+ comment: zod
+ .string()
+ .max(fieldNotesPartialUpdateBodyCommentMax)
+ .optional()
+ .describe('The note the user wrote about the element.'),
+ field_note_status: zod
+ .enum(['pending', 'acknowledged', 'resolved', 'dismissed'])
+ .describe(
+ '* `pending` - Pending\n* `acknowledged` - Acknowledged\n* `resolved` - Resolved\n* `dismissed` - Dismissed'
+ )
+ .optional()
+ .describe(
+ 'Lifecycle of the field note: pending, acknowledged, resolved, or dismissed. Ignored on create.\n\n* `pending` - Pending\n* `acknowledged` - Acknowledged\n* `resolved` - Resolved\n* `dismissed` - Dismissed'
+ ),
+ resolution: zod
+ .string()
+ .nullish()
+ .describe('Optional note left by the agent when acknowledging, resolving, or dismissing the field note.'),
+ url: zod
+ .string()
+ .max(fieldNotesPartialUpdateBodyUrlMax)
+ .optional()
+ .describe('Full URL of the page the field note was made on.'),
+ host: zod
+ .string()
+ .max(fieldNotesPartialUpdateBodyHostMax)
+ .optional()
+ .describe('Hostname of the page, used to scope field notes to a site.'),
+ pathname: zod.string().max(fieldNotesPartialUpdateBodyPathnameMax).nullish().describe('Path portion of the URL.'),
+ selector: zod
+ .string()
+ .max(fieldNotesPartialUpdateBodySelectorMax)
+ .optional()
+ .describe('CSS selector that locates the element on the page.'),
+ element_text: zod
+ .string()
+ .max(fieldNotesPartialUpdateBodyElementTextMax)
+ .nullish()
+ .describe('Visible text of the element, if any.'),
+ element_chain: zod
+ .string()
+ .max(fieldNotesPartialUpdateBodyElementChainMax)
+ .nullish()
+ .describe('Serialized autocapture-style element chain from the element up to the document root.'),
+ element_context: zod
+ .record(zod.string(), zod.unknown())
+ .optional()
+ .describe('Structured element metadata (inferred selectors, attributes, component hints).'),
+ viewport: zod
+ .object({
+ width: zod.number().optional().describe('Viewport width in pixels.'),
+ height: zod.number().optional().describe('Viewport height in pixels.'),
+ })
+ .nullish()
+ .describe('Viewport size when the field note was made, as {width, height}.'),
+ screenshot_url: zod
+ .string()
+ .max(fieldNotesPartialUpdateBodyScreenshotUrlMax)
+ .nullish()
+ .describe('URL of an uploaded screenshot captured with the field_note.'),
+})
diff --git a/services/mcp/src/lib/oauth-scopes.generated.ts b/services/mcp/src/lib/oauth-scopes.generated.ts
index c2b6754e8324..da0358b9dc9f 100644
--- a/services/mcp/src/lib/oauth-scopes.generated.ts
+++ b/services/mcp/src/lib/oauth-scopes.generated.ts
@@ -165,6 +165,8 @@ export const OAUTH_SCOPES_SUPPORTED = [
'task:write',
'tracing:read',
'tracing:write',
+ 'field_note:read',
+ 'field_note:write',
'uploaded_media:read',
'uploaded_media:write',
'usage_metric:read',
diff --git a/services/mcp/src/tools/generated/field_notes.ts b/services/mcp/src/tools/generated/field_notes.ts
new file mode 100644
index 000000000000..72d430b802af
--- /dev/null
+++ b/services/mcp/src/tools/generated/field_notes.ts
@@ -0,0 +1,140 @@
+// AUTO-GENERATED from products/field_notes/mcp/tools.yaml + OpenAPI — do not edit
+import { z } from 'zod'
+
+import type { Schemas } from '@/api/generated'
+import {
+ FieldNotesListQueryParams,
+ FieldNotesPartialUpdateBody,
+ FieldNotesPartialUpdateParams,
+ FieldNotesRetrieveParams,
+} from '@/generated/field_notes/api'
+import { withPostHogUrl, pickResponseFields, type WithPostHogUrl } from '@/tools/tool-utils'
+import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'
+
+const FieldNotesGetSchema = FieldNotesRetrieveParams.omit({ project_id: true })
+
+const fieldNotesGet = (): ToolBase<typeof FieldNotesGetSchema, WithPostHogUrl<Schemas.FieldNote>> => ({
+ name: 'field-notes-get',
+ schema: FieldNotesGetSchema,
+ handler: async (context: Context, params: z.infer<typeof FieldNotesGetSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.FieldNote>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/field_notes/${encodeURIComponent(String(params.id))}/`,
+ })
+ return await withPostHogUrl(context, result, `/field_notes/${result.id}`)
+ },
+})
+
+const FieldNotesListSchema = FieldNotesListQueryParams
+
+const fieldNotesList = (): ToolBase<typeof FieldNotesListSchema, WithPostHogUrl<Schemas.PaginatedFieldNoteList>> => ({
+ name: 'field-notes-list',
+ schema: FieldNotesListSchema,
+ handler: async (context: Context, params: z.infer<typeof FieldNotesListSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.PaginatedFieldNoteList>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/field_notes/`,
+ query: {
+ field_note_status: params.field_note_status,
+ host: params.host,
+ limit: params.limit,
+ offset: params.offset,
+ },
+ })
+ const filtered = {
+ ...result,
+ results: (result.results ?? []).map((item: any) =>
+ pickResponseFields(item, [
+ 'id',
+ 'comment',
+ 'field_note_status',
+ 'resolution',
+ 'url',
+ 'host',
+ 'pathname',
+ 'selector',
+ 'element_text',
+ 'screenshot_url',
+ 'created_at',
+ 'created_by',
+ ])
+ ),
+ } as typeof result
+ return await withPostHogUrl(
+ context,
+ {
+ ...filtered,
+ results: await Promise.all(
+ (filtered.results ?? []).map((item) => withPostHogUrl(context, item, `/field_notes/${item.id}`))
+ ),
+ },
+ '/field_notes'
+ )
+ },
+})
+
+const FieldNotesPartialUpdateSchema = FieldNotesPartialUpdateParams.omit({ project_id: true }).extend(
+ FieldNotesPartialUpdateBody.shape
+)
+
+const fieldNotesPartialUpdate = (): ToolBase<
+ typeof FieldNotesPartialUpdateSchema,
+ WithPostHogUrl<Schemas.FieldNote>
+> => ({
+ name: 'field-notes-partial-update',
+ schema: FieldNotesPartialUpdateSchema,
+ handler: async (context: Context, params: z.infer<typeof FieldNotesPartialUpdateSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.comment !== undefined) {
+ body['comment'] = params.comment
+ }
+ if (params.field_note_status !== undefined) {
+ body['field_note_status'] = params.field_note_status
+ }
+ if (params.resolution !== undefined) {
+ body['resolution'] = params.resolution
+ }
+ if (params.url !== undefined) {
+ body['url'] = params.url
+ }
+ if (params.host !== undefined) {
+ body['host'] = params.host
+ }
+ if (params.pathname !== undefined) {
+ body['pathname'] = params.pathname
+ }
+ if (params.selector !== undefined) {
+ body['selector'] = params.selector
+ }
+ if (params.element_text !== undefined) {
+ body['element_text'] = params.element_text
+ }
+ if (params.element_chain !== undefined) {
+ body['element_chain'] = params.element_chain
+ }
+ if (params.element_context !== undefined) {
+ body['element_context'] = params.element_context
+ }
+ if (params.viewport !== undefined) {
+ body['viewport'] = params.viewport
+ }
+ if (params.screenshot_url !== undefined) {
+ body['screenshot_url'] = params.screenshot_url
+ }
+ const result = await context.api.request<Schemas.FieldNote>({
+ method: 'PATCH',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/field_notes/${encodeURIComponent(String(params.id))}/`,
+ body,
+ })
+ return await withPostHogUrl(context, result, `/field_notes/${result.id}`)
+ },
+})
+
+export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
+ 'field-notes-get': fieldNotesGet,
+ 'field-notes-list': fieldNotesList,
+ 'field-notes-partial-update': fieldNotesPartialUpdate,
+}
diff --git a/services/mcp/src/tools/generated/index.ts b/services/mcp/src/tools/generated/index.ts
index 3cf1149f126f..05b2bcf232b9 100644
--- a/services/mcp/src/tools/generated/index.ts
+++ b/services/mcp/src/tools/generated/index.ts
@@ -22,6 +22,7 @@ import { GENERATED_TOOLS as engineering_analytics } from './engineering_analytic
import { GENERATED_TOOLS as error_tracking } from './error_tracking'
import { GENERATED_TOOLS as experiments } from './experiments'
import { GENERATED_TOOLS as feature_flags } from './feature_flags'
+import { GENERATED_TOOLS as field_notes } from './field_notes'
import { GENERATED_TOOLS as health_issues } from './health_issues'
import { GENERATED_TOOLS as integrations } from './integrations'
import { GENERATED_TOOLS as logs } from './logs'
@@ -66,6 +67,7 @@ export const GENERATED_TOOL_MAP: Record<string, () => ToolBase<ZodObjectAny>> =
...error_tracking,
...experiments,
...feature_flags,
+ ...field_notes,
...health_issues,
...integrations,
...logs,
diff --git a/services/mcp/tests/unit/tool-filtering.test.ts b/services/mcp/tests/unit/tool-filtering.test.ts
index bae9e3e3caf0..cf43e4ef8882 100644
--- a/services/mcp/tests/unit/tool-filtering.test.ts
+++ b/services/mcp/tests/unit/tool-filtering.test.ts
@@ -747,9 +747,10 @@ describe('Tool Filtering - Feature Flags', () => {
'heatmaps-mcp',
'marketing-analytics-mcp',
'product-business-knowledge',
+ 'field-notes',
])
)
- expect(flags).toHaveLength(15)
+ expect(flags).toHaveLength(16)
})
// Exercise the real predicate (toolPassesFlagGate) over hand-rolled entries
diff --git a/tach.toml b/tach.toml
index 9c47bf5f68f0..68e800922e55 100644
--- a/tach.toml
+++ b/tach.toml
@@ -855,3 +855,8 @@ layer = "modules"
path = "products.annotations"
depends_on = ["posthog", "products.product_analytics", "products.dashboards"]
layer = "modules"
+
+[[modules]]
+path = "products.field_notes"
+depends_on = ["posthog"]
+layer = "modules"