@waniwani/sdk 0.4.3 → 0.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -313,11 +313,225 @@ type RegisteredResource = {
313
313
  register: (server: McpServer) => Promise<void>;
314
314
  };
315
315
 
316
+ interface SearchResult {
317
+ source: string;
318
+ heading: string;
319
+ content: string;
320
+ score: number;
321
+ metadata?: Record<string, string>;
322
+ }
323
+ /** A file to ingest into the knowledge base */
324
+ interface KbIngestFile {
325
+ /** Filename (used as chunk source identifier) */
326
+ filename: string;
327
+ /** Markdown content of the file */
328
+ content: string;
329
+ /** Arbitrary key-value metadata attached to all chunks from this file */
330
+ metadata?: Record<string, string>;
331
+ }
332
+ /** Response from the ingest endpoint */
333
+ interface KbIngestResult {
334
+ /** Number of chunks created from the ingested files */
335
+ chunksIngested: number;
336
+ /** Number of files successfully processed */
337
+ filesProcessed: number;
338
+ }
339
+ /** Options for the search method */
340
+ interface KbSearchOptions {
341
+ /** Number of results to return (1-20, default 5) */
342
+ topK?: number;
343
+ /** Minimum similarity score threshold (0-1, default 0.3) */
344
+ minScore?: number;
345
+ /** Filter results to chunks whose metadata contains all these key-value pairs (exact match) */
346
+ metadata?: Record<string, string>;
347
+ }
348
+ /** A source entry in the knowledge base */
349
+ interface KbSource {
350
+ /** Source filename */
351
+ source: string;
352
+ /** Number of chunks from this source */
353
+ chunkCount: number;
354
+ /** ISO timestamp of when the source was first ingested */
355
+ createdAt: string;
356
+ }
357
+ /** KB client for server-side knowledge base operations */
358
+ interface KbClient {
359
+ /**
360
+ * Ingest files into the knowledge base.
361
+ *
362
+ * **Warning**: This is destructive — it deletes ALL existing chunks
363
+ * for the environment before ingesting the new files.
364
+ */
365
+ ingest(files: KbIngestFile[]): Promise<KbIngestResult>;
366
+ /** Search the knowledge base for relevant chunks */
367
+ search(query: string, options?: KbSearchOptions): Promise<SearchResult[]>;
368
+ /** List all sources in the knowledge base */
369
+ sources(): Promise<KbSource[]>;
370
+ }
371
+
372
+ type EventType = "session.started" | "tool.called" | "quote.requested" | "quote.succeeded" | "quote.failed" | "link.clicked" | "purchase.completed" | "widget_render" | "widget_click" | "widget_link_click" | "widget_error" | "widget_scroll" | "widget_form_field" | "widget_form_submit" | "user.identified";
373
+ interface ToolCalledProperties {
374
+ name?: string;
375
+ type?: "pricing" | "product_info" | "availability" | "support" | "other";
376
+ }
377
+ interface QuoteSucceededProperties {
378
+ amount?: number;
379
+ currency?: string;
380
+ }
381
+ interface LinkClickedProperties {
382
+ url?: string;
383
+ }
384
+ interface PurchaseCompletedProperties {
385
+ amount?: number;
386
+ currency?: string;
387
+ }
388
+ interface TrackingContext {
389
+ /**
390
+ * MCP request metadata passed through to the API.
391
+ *
392
+ * Location varies by MCP library:
393
+ * - `@vercel/mcp-handler`: `extra._meta`
394
+ * - `@modelcontextprotocol/sdk`: `request.params._meta`
395
+ */
396
+ meta?: Record<string, unknown>;
397
+ /** Legacy metadata field supported for backward compatibility. */
398
+ metadata?: Record<string, unknown>;
399
+ /** Optional explicit correlation fields. */
400
+ sessionId?: string;
401
+ traceId?: string;
402
+ requestId?: string;
403
+ correlationId?: string;
404
+ externalUserId?: string;
405
+ /** Optional explicit envelope fields. */
406
+ eventId?: string;
407
+ timestamp?: string | Date;
408
+ source?: string;
409
+ }
410
+ /**
411
+ * Modern tracking shape (preferred).
412
+ */
413
+ interface BaseTrackEvent extends TrackingContext {
414
+ event: EventType;
415
+ properties?: Record<string, unknown>;
416
+ }
417
+ type TrackEvent = ({
418
+ event: "session.started";
419
+ } & BaseTrackEvent) | ({
420
+ event: "tool.called";
421
+ properties?: ToolCalledProperties;
422
+ } & BaseTrackEvent) | ({
423
+ event: "quote.requested";
424
+ } & BaseTrackEvent) | ({
425
+ event: "quote.succeeded";
426
+ properties?: QuoteSucceededProperties;
427
+ } & BaseTrackEvent) | ({
428
+ event: "quote.failed";
429
+ } & BaseTrackEvent) | ({
430
+ event: "link.clicked";
431
+ properties?: LinkClickedProperties;
432
+ } & BaseTrackEvent) | ({
433
+ event: "purchase.completed";
434
+ properties?: PurchaseCompletedProperties;
435
+ } & BaseTrackEvent) | ({
436
+ event: "user.identified";
437
+ } & BaseTrackEvent);
438
+ /**
439
+ * Legacy tracking shape supported for existing integrations.
440
+ */
441
+ interface LegacyTrackEvent extends TrackingContext {
442
+ eventType: EventType;
443
+ properties?: Record<string, unknown>;
444
+ toolName?: string;
445
+ toolType?: ToolCalledProperties["type"];
446
+ quoteAmount?: number;
447
+ quoteCurrency?: string;
448
+ linkUrl?: string;
449
+ purchaseAmount?: number;
450
+ purchaseCurrency?: string;
451
+ }
452
+ /**
453
+ * Public track input accepted by `client.track()`.
454
+ */
455
+ type TrackInput = TrackEvent | LegacyTrackEvent;
456
+ interface TrackingConfig {
457
+ /** Events API V2 endpoint path. */
458
+ endpointPath?: string;
459
+ /** Periodic flush interval for buffered events. */
460
+ flushIntervalMs?: number;
461
+ /** Max events per HTTP batch send. */
462
+ maxBatchSize?: number;
463
+ /** Max in-memory buffer size before oldest items are dropped. */
464
+ maxBufferSize?: number;
465
+ /** Number of retries for retryable failures. */
466
+ maxRetries?: number;
467
+ /** Retry backoff base delay. */
468
+ retryBaseDelayMs?: number;
469
+ /** Retry backoff max delay. */
470
+ retryMaxDelayMs?: number;
471
+ /** Default shutdown timeout when none is provided. */
472
+ shutdownTimeoutMs?: number;
473
+ }
474
+ interface TrackingShutdownOptions {
475
+ timeoutMs?: number;
476
+ }
477
+ interface TrackingShutdownResult {
478
+ timedOut: boolean;
479
+ pendingEvents: number;
480
+ }
481
+ /**
482
+ * Tracking module methods for WaniWaniClient.
483
+ */
484
+ interface TrackingClient {
485
+ /**
486
+ * Send a one-shot identify event for a user.
487
+ * userId can be any string: an email, an internal ID, etc.
488
+ */
489
+ identify: (userId: string, properties?: Record<string, unknown>, meta?: Record<string, unknown>) => Promise<{
490
+ eventId: string;
491
+ }>;
492
+ /**
493
+ * Track an event using modern or legacy input shape.
494
+ * Returns a deterministic event id immediately after enqueue.
495
+ */
496
+ track: (event: TrackInput) => Promise<{
497
+ eventId: string;
498
+ }>;
499
+ /**
500
+ * Flush all currently buffered events.
501
+ */
502
+ flush: () => Promise<void>;
503
+ /**
504
+ * Flush and stop the transport.
505
+ */
506
+ shutdown: (options?: TrackingShutdownOptions) => Promise<TrackingShutdownResult>;
507
+ }
508
+
509
+ /**
510
+ * A request-scoped WaniWani client with meta pre-attached.
511
+ *
512
+ * Available as `context.waniwani` inside `createTool` handlers and flow nodes
513
+ * when the server is wrapped with `withWaniwani()`.
514
+ */
515
+ interface ScopedWaniWaniClient {
516
+ /** Track an event — request meta is automatically merged. */
517
+ track(event: TrackInput): Promise<{
518
+ eventId: string;
519
+ }>;
520
+ /** Identify a user — request meta is automatically merged. */
521
+ identify(userId: string, properties?: Record<string, unknown>): Promise<{
522
+ eventId: string;
523
+ }>;
524
+ /** Knowledge base client (no meta needed). */
525
+ readonly kb: KbClient;
526
+ }
527
+
316
528
  type ToolHandlerContext = {
317
529
  /** Raw MCP request extra data (includes _meta for session extraction) */
318
530
  extra?: {
319
531
  _meta?: Record<string, unknown>;
320
532
  };
533
+ /** Session-scoped WaniWani client — available when the server is wrapped with withWaniwani() */
534
+ waniwani?: ScopedWaniWaniClient;
321
535
  };
322
536
  type ToolConfig<TInput extends ZodRawShapeCompat> = {
323
537
  /** The resource (HTML template) this tool renders. When present, tool returns structuredContent + widget _meta. */
@@ -498,6 +712,8 @@ type NodeContext<TState> = {
498
712
  interrupt: TypedInterrupt<TState>;
499
713
  /** Create a widget signal — pause and show a UI widget */
500
714
  showWidget: TypedShowWidget<TState>;
715
+ /** Session-scoped WaniWani client — available when the server is wrapped with withWaniwani() */
716
+ waniwani?: ScopedWaniWaniClient;
501
717
  };
502
718
  /**
503
719
  * Node handler — receives a context object and returns a signal or state updates.
@@ -585,10 +801,7 @@ type InterruptQuestionData = {
585
801
  suggestions?: string[];
586
802
  context?: string;
587
803
  };
588
- type FlowContentBase = {
589
- flowToken?: string;
590
- };
591
- type FlowInterruptContent = FlowContentBase & {
804
+ type FlowInterruptContent = {
592
805
  status: "interrupt";
593
806
  /** Single-question shorthand */
594
807
  question?: string;
@@ -598,7 +811,7 @@ type FlowInterruptContent = FlowContentBase & {
598
811
  questions?: InterruptQuestionData[];
599
812
  context?: string;
600
813
  };
601
- type FlowWidgetContent = FlowContentBase & {
814
+ type FlowWidgetContent = {
602
815
  status: "widget";
603
816
  /** Display tool to call */
604
817
  tool: string;
@@ -608,10 +821,10 @@ type FlowWidgetContent = FlowContentBase & {
608
821
  /** Whether the widget expects user interaction before continuing */
609
822
  interactive?: boolean;
610
823
  };
611
- type FlowCompleteContent = FlowContentBase & {
824
+ type FlowCompleteContent = {
612
825
  status: "complete";
613
826
  };
614
- type FlowErrorContent = FlowContentBase & {
827
+ type FlowErrorContent = {
615
828
  status: "error";
616
829
  error: string;
617
830
  };
@@ -701,22 +914,6 @@ declare function createFlow<const TSchema extends Record<string, z.ZodType>>(con
701
914
  state: TSchema;
702
915
  }): StateGraph<InferFlowState<TSchema>>;
703
916
 
704
- /**
705
- * Opaque compressed token for flow state round-tripping.
706
- *
707
- * Flow state is compressed (zlib deflate) then base64-encoded. This produces
708
- * a token that:
709
- * 1. Looks like random noise — models can't mentally decode it
710
- * 2. Is smaller than raw base64 (~30% compression on typical state)
711
- * 3. The model treats it as an opaque string and passes it back unchanged
712
- *
713
- * Only encoded/decoded on the server (Node.js). Browser code should never
714
- * need to decode flow tokens.
715
- */
716
-
717
- declare function encodeFlowToken(data: FlowTokenContent): string;
718
- declare function decodeFlowToken(token: string): FlowTokenContent | null;
719
-
720
917
  type WithDecodedState = {
721
918
  decodedState: FlowTokenContent | null;
722
919
  };
@@ -814,215 +1011,6 @@ interface TrackingRouteOptions {
814
1011
  */
815
1012
  declare function createTrackingRoute(options?: TrackingRouteOptions): (request: Request) => Promise<Response>;
816
1013
 
817
- interface SearchResult {
818
- source: string;
819
- heading: string;
820
- content: string;
821
- score: number;
822
- }
823
- /** A file to ingest into the knowledge base */
824
- interface KbIngestFile {
825
- /** Filename (used as chunk source identifier) */
826
- filename: string;
827
- /** Markdown content of the file */
828
- content: string;
829
- }
830
- /** Response from the ingest endpoint */
831
- interface KbIngestResult {
832
- /** Number of chunks created from the ingested files */
833
- chunksIngested: number;
834
- /** Number of files successfully processed */
835
- filesProcessed: number;
836
- }
837
- /** Options for the search method */
838
- interface KbSearchOptions {
839
- /** Number of results to return (1-20, default 5) */
840
- topK?: number;
841
- /** Minimum similarity score threshold (0-1, default 0.3) */
842
- minScore?: number;
843
- }
844
- /** A source entry in the knowledge base */
845
- interface KbSource {
846
- /** Source filename */
847
- source: string;
848
- /** Number of chunks from this source */
849
- chunkCount: number;
850
- /** ISO timestamp of when the source was first ingested */
851
- createdAt: string;
852
- }
853
- /** KB client for server-side knowledge base operations */
854
- interface KbClient {
855
- /**
856
- * Ingest files into the knowledge base.
857
- *
858
- * **Warning**: This is destructive — it deletes ALL existing chunks
859
- * for the environment before ingesting the new files.
860
- */
861
- ingest(files: KbIngestFile[]): Promise<KbIngestResult>;
862
- /** Search the knowledge base for relevant chunks */
863
- search(query: string, options?: KbSearchOptions): Promise<SearchResult[]>;
864
- /** List all sources in the knowledge base */
865
- sources(): Promise<KbSource[]>;
866
- }
867
-
868
- type EventType = "session.started" | "tool.called" | "quote.requested" | "quote.succeeded" | "quote.failed" | "link.clicked" | "purchase.completed" | "widget_render" | "widget_click" | "widget_link_click" | "widget_error" | "widget_scroll" | "widget_form_field" | "widget_form_submit" | "user.identified";
869
- interface ToolCalledProperties {
870
- name?: string;
871
- type?: "pricing" | "product_info" | "availability" | "support" | "other";
872
- }
873
- interface QuoteSucceededProperties {
874
- amount?: number;
875
- currency?: string;
876
- }
877
- interface LinkClickedProperties {
878
- url?: string;
879
- }
880
- interface PurchaseCompletedProperties {
881
- amount?: number;
882
- currency?: string;
883
- }
884
- interface TrackingContext {
885
- /**
886
- * MCP request metadata passed through to the API.
887
- *
888
- * Location varies by MCP library:
889
- * - `@vercel/mcp-handler`: `extra._meta`
890
- * - `@modelcontextprotocol/sdk`: `request.params._meta`
891
- */
892
- meta?: Record<string, unknown>;
893
- /** Legacy metadata field supported for backward compatibility. */
894
- metadata?: Record<string, unknown>;
895
- /** Optional explicit correlation fields. */
896
- sessionId?: string;
897
- traceId?: string;
898
- requestId?: string;
899
- correlationId?: string;
900
- externalUserId?: string;
901
- /** Optional explicit envelope fields. */
902
- eventId?: string;
903
- timestamp?: string | Date;
904
- source?: string;
905
- }
906
- /**
907
- * Modern tracking shape (preferred).
908
- */
909
- interface BaseTrackEvent extends TrackingContext {
910
- event: EventType;
911
- properties?: Record<string, unknown>;
912
- }
913
- type TrackEvent = ({
914
- event: "session.started";
915
- } & BaseTrackEvent) | ({
916
- event: "tool.called";
917
- properties?: ToolCalledProperties;
918
- } & BaseTrackEvent) | ({
919
- event: "quote.requested";
920
- } & BaseTrackEvent) | ({
921
- event: "quote.succeeded";
922
- properties?: QuoteSucceededProperties;
923
- } & BaseTrackEvent) | ({
924
- event: "quote.failed";
925
- } & BaseTrackEvent) | ({
926
- event: "link.clicked";
927
- properties?: LinkClickedProperties;
928
- } & BaseTrackEvent) | ({
929
- event: "purchase.completed";
930
- properties?: PurchaseCompletedProperties;
931
- } & BaseTrackEvent) | ({
932
- event: "user.identified";
933
- } & BaseTrackEvent);
934
- /**
935
- * Legacy tracking shape supported for existing integrations.
936
- */
937
- interface LegacyTrackEvent extends TrackingContext {
938
- eventType: EventType;
939
- properties?: Record<string, unknown>;
940
- toolName?: string;
941
- toolType?: ToolCalledProperties["type"];
942
- quoteAmount?: number;
943
- quoteCurrency?: string;
944
- linkUrl?: string;
945
- purchaseAmount?: number;
946
- purchaseCurrency?: string;
947
- }
948
- /**
949
- * Public track input accepted by `client.track()`.
950
- */
951
- type TrackInput = TrackEvent | LegacyTrackEvent;
952
- interface TrackingConfig {
953
- /** Events API V2 endpoint path. */
954
- endpointPath?: string;
955
- /** Periodic flush interval for buffered events. */
956
- flushIntervalMs?: number;
957
- /** Max events per HTTP batch send. */
958
- maxBatchSize?: number;
959
- /** Max in-memory buffer size before oldest items are dropped. */
960
- maxBufferSize?: number;
961
- /** Number of retries for retryable failures. */
962
- maxRetries?: number;
963
- /** Retry backoff base delay. */
964
- retryBaseDelayMs?: number;
965
- /** Retry backoff max delay. */
966
- retryMaxDelayMs?: number;
967
- /** Default shutdown timeout when none is provided. */
968
- shutdownTimeoutMs?: number;
969
- }
970
- interface TrackingShutdownOptions {
971
- timeoutMs?: number;
972
- }
973
- interface TrackingShutdownResult {
974
- timedOut: boolean;
975
- pendingEvents: number;
976
- }
977
- /**
978
- * Tracking module methods for WaniWaniClient.
979
- */
980
- interface TrackingClient {
981
- /**
982
- * Send a one-shot identify event for a user.
983
- * userId can be any string: an email, an internal ID, etc.
984
- */
985
- identify: (userId: string, properties?: Record<string, unknown>) => Promise<{
986
- eventId: string;
987
- }>;
988
- /**
989
- * Track an event using modern or legacy input shape.
990
- * Returns a deterministic event id immediately after enqueue.
991
- */
992
- track: (event: TrackInput) => Promise<{
993
- eventId: string;
994
- }>;
995
- /**
996
- * Flush all currently buffered events.
997
- */
998
- flush: () => Promise<void>;
999
- /**
1000
- * Flush and stop the transport.
1001
- */
1002
- shutdown: (options?: TrackingShutdownOptions) => Promise<TrackingShutdownResult>;
1003
- }
1004
-
1005
- interface WaniWaniConfig {
1006
- /**
1007
- * Your MCP environment API key
1008
- *
1009
- * Defaults to process.env.WANIWANI_API_KEY if not provided
1010
- *
1011
- * To create one, visit:
1012
- * https://app.waniwani.com/mcp/environments
1013
- */
1014
- apiKey?: string;
1015
- /**
1016
- * The base URL of the WaniWani API
1017
- *
1018
- * Defaults to https://app.waniwani.ai
1019
- */
1020
- baseUrl?: string;
1021
- /**
1022
- * Tracking transport behavior.
1023
- */
1024
- tracking?: TrackingConfig;
1025
- }
1026
1014
  /**
1027
1015
  * WaniWani SDK Client
1028
1016
  *
@@ -1044,21 +1032,18 @@ interface InternalConfig {
1044
1032
  tracking: Required<TrackingConfig>;
1045
1033
  }
1046
1034
 
1047
- type WaniwaniTracker = Pick<WaniWaniClient, "flush" | "track" | "_config">;
1035
+ type WaniwaniTracker = Pick<WaniWaniClient, "flush" | "track" | "identify" | "kb" | "_config">;
1036
+
1048
1037
  type UnknownRecord = Record<string, unknown>;
1049
1038
  /**
1050
1039
  * Options for withWaniwani().
1051
1040
  */
1052
1041
  type WithWaniwaniOptions = {
1053
1042
  /**
1054
- * Optional pre-built WaniWani client.
1055
- * When omitted, a new client is created from `config`.
1056
- */
1057
- client?: WaniwaniTracker;
1058
- /**
1059
- * WaniWani client config used when `client` is omitted.
1043
+ * The WaniWani client instance. All tracking calls made through this client
1044
+ * during tool execution will automatically include session metadata.
1060
1045
  */
1061
- config?: WaniWaniConfig;
1046
+ client: WaniwaniTracker;
1062
1047
  /**
1063
1048
  * Optional explicit tool type. Defaults to `"other"`.
1064
1049
  */
@@ -1096,6 +1081,6 @@ type WithWaniwaniOptions = {
1096
1081
  * into tool response `_meta.waniwani` so browser widgets can post events
1097
1082
  * directly to the WaniWani backend without a server-side proxy.
1098
1083
  */
1099
- declare function withWaniwani(server: McpServer, options?: WithWaniwaniOptions): McpServer;
1084
+ declare function withWaniwani(server: McpServer, options: WithWaniwaniOptions): McpServer;
1100
1085
 
1101
- export { type ConditionFn, END, type FlowConfig, type FlowTestResult, type HostContext, type InferFlowState, type InterruptSignal, type NodeContext, type NodeHandler, type RegisteredFlow, type RegisteredResource, type RegisteredTool, type ResourceConfig, START, StateGraph, type ToolCallResult, type ToolConfig, type ToolHandler, type ToolHandlerContext, type ToolResult, type ToolToolCallback, type TrackingRouteOptions, type TypedInterrupt, type TypedShowWidget, type UnifiedWidgetClient, type WidgetCSP, type WidgetPlatform, type WidgetSignal, type WithWaniwaniOptions, createFlow, createFlowTestHarness, createResource, createTool, createTrackingRoute, decodeFlowToken, detectPlatform, encodeFlowToken, isMCPApps, isOpenAI, registerTools, withWaniwani };
1086
+ export { type ConditionFn, END, type FlowConfig, type FlowTestResult, type HostContext, type InferFlowState, type InterruptSignal, type NodeContext, type NodeHandler, type RegisteredFlow, type RegisteredResource, type RegisteredTool, type ResourceConfig, START, type ScopedWaniWaniClient, StateGraph, type ToolCallResult, type ToolConfig, type ToolHandler, type ToolHandlerContext, type ToolResult, type ToolToolCallback, type TrackingRouteOptions, type TypedInterrupt, type TypedShowWidget, type UnifiedWidgetClient, type WidgetCSP, type WidgetPlatform, type WidgetSignal, type WithWaniwaniOptions, createFlow, createFlowTestHarness, createResource, createTool, createTrackingRoute, detectPlatform, isMCPApps, isOpenAI, registerTools, withWaniwani };