Skip to content

Chat page add SystemPrompt and Authorization Textbox - #180

Merged
iFurySt merged 2 commits into
AmoyLab:mainfrom
boston008:chat-systemprompt-authorization-textbox
Jul 9, 2025
Merged

iFurySt merged 2 commits into
AmoyLab:mainfrom
boston008:chat-systemprompt-authorization-textbox

Conversation

@boston008

@boston008 boston008 commented Jul 2, 2025 •

Copy link
Copy Markdown
Contributor

In Chat page add SystemPrompt and Authorization Textbox.
User has ability to add SystemPrompt & Authorization Code in Chat
SystemPrompt is send to llm with user input message.
Authorization textbox value is passthrough to the Rest API
SystemPrompt is saved to database,

Summary by Sourcery

Add a customizable system prompt feature and authorization token support to the chat interface, including persistence, API endpoints, and UI enhancements.

New Features:

  • Introduce a system prompt input and modal in the chat UI with REST endpoints to load and save prompts per user
  • Add an authorization token textbox in the chat UI and pass the token into MCPService.connect for authenticated tool connections
  • Implement new database migrations, model, and persistence methods for SystemPrompt across MySQL, Postgres, and SQLite
  • Expose API handlers and client services for getting and saving the system prompt

Enhancements:

  • Sanitize and map tool names for external LLM providers with helper functions and preserve original names in tool calls
  • Unify state updates in message handling to use typed callback patterns and filter out incomplete bot messages
  • Extend MCPService.connect to accept custom auth headers and add reconnection options

Chat Add SystemPrompt and Authorization Textbox.
SystemPrompt is saved to database
Authorization textbox value is passthrough to  the Rest API
@sourcery-ai

sourcery-ai Bot commented Jul 2, 2025 •

Copy link
Copy Markdown
Contributor

Reviewer's Guide

This PR enhances the Chat page by adding a per-user system prompt editor and an authorization token input, wiring them through the message pipeline and MCP service, introducing frontend services and backend persistence for system prompts, and sanitizing tool names for consistent tool calls.

Sequence diagram for saving and loading System Prompt

sequenceDiagram
    actor User
    participant ChatPage as Chat Page (Frontend)
    participant SystemPromptAPI as SystemPrompt API (Backend)
    participant DB as Database

    User->>ChatPage: Open Chat page
    ChatPage->>SystemPromptAPI: GET /chat/systemprompt
    SystemPromptAPI->>DB: GetSystemPrompt(userID)
    DB-->>SystemPromptAPI: SystemPrompt
    SystemPromptAPI-->>ChatPage: { prompt }
    User->>ChatPage: Edit and Save System Prompt
    ChatPage->>SystemPromptAPI: PUT /chat/systemprompt { prompt }
    SystemPromptAPI->>DB: SaveSystemPrompt(userID, prompt)
    DB-->>SystemPromptAPI: OK
    SystemPromptAPI-->>ChatPage: { success: true }
Loading

Sequence diagram for sending chat message with System Prompt and Authorization Token

sequenceDiagram
    actor User
    participant ChatPage as Chat Page (Frontend)
    participant LLMService as LLM Chat Service
    participant MCPService as MCP Service
    participant MCPServer as MCP Server

    User->>ChatPage: Enter message, System Prompt, Auth Token
    ChatPage->>LLMService: sendMessage(..., systemPrompt, authToken)
    LLMService->>MCPService: connect(..., authToken)
    MCPService->>MCPServer: Connect with Authorization header
    LLMService->>MCPService: getTools(...)
    MCPService->>MCPServer: Request tools (with Auth header)
    LLMService->>MCPService: send message (with systemPrompt)
    MCPService->>MCPServer: Forward message (with systemPrompt, Auth header)
    MCPServer-->>MCPService: LLM response
    MCPService-->>LLMService: LLM response
    LLMService-->>ChatPage: Display response
Loading

ER diagram for new SystemPrompt table

erDiagram
    USER ||--o| SYSTEM_PROMPT : has
    SYSTEM_PROMPT {
      uint UserID PK "Primary key, foreign key to User.ID"
      string Prompt "System prompt text"
      time UpdatedAt "Last update time"
    }
Loading

Class diagram for SystemPrompt backend model and database interface

classDiagram
    class SystemPrompt {
      +uint UserID
      +string Prompt
      +time.Time UpdatedAt
    }
    class Database {
      +GetSystemPrompt(ctx, userID) string
      +SaveSystemPrompt(ctx, userID, prompt) error
    }
    Database <|.. MySQL
    Database <|.. Postgres
    Database <|.. SQLite
    MySQL : +GetSystemPrompt(ctx, userID) string
    MySQL : +SaveSystemPrompt(ctx, userID, prompt) error
    Postgres : +GetSystemPrompt(ctx, userID) string
    Postgres : +SaveSystemPrompt(ctx, userID, prompt) error
    SQLite : +GetSystemPrompt(ctx, userID) string
    SQLite : +SaveSystemPrompt(ctx, userID, prompt) error
    User "1" -- "0..1" SystemPrompt : owns
Loading

Class diagram for frontend SystemPrompt service

classDiagram
    class SystemPromptService {
      +getSystemPrompt() string
      +saveSystemPrompt(prompt string) void
    }
Loading

File-Level Changes

Change Details Files
Add system prompt and authorization token inputs to the chat interface
  • Define systemPrompt, systemPromptDraft, isSystemPromptModalOpen and authToken states
  • Inject systemPrompt into outgoing messages via buildLLMMessages
  • Pass authToken to mcpService.connect and include it in effect dependencies
  • Implement modal dialog for editing and saving systemPrompt
web/src/pages/chat/llm-chat-interface.tsx
Sanitize tool names and track original names for API calls
  • Implement sanitizeToolName and getSanitizedToolNameMap utilities
  • Patch outgoing toolCalls to include originalName alongside sanitized names
  • Update ChatMessage to use originalName for display and parsing
web/src/pages/chat/llm-chat-interface.tsx
web/src/pages/chat/components/chat-message.tsx
Extend MCP service to accept auth tokens and custom headers
  • Update connect signature to accept authToken and optional headerName
  • Build requestInit.headers with Authorization or custom header
  • Add reconnectionOptions to StreamableHTTPClientTransport
web/src/services/mcp.ts
Add frontend systemPrompt service for API calls
  • Create getSystemPrompt and saveSystemPrompt functions calling /chat/systemprompt
web/src/services/systemprompt.ts
Persist system prompts in DB and expose GET/PUT endpoints
  • Define SystemPrompt model and include it in AutoMigrate for MySQL/Postgres/SQLite
  • Extend Database interface with GetSystemPrompt and SaveSystemPrompt
  • Implement handler methods for GET and PUT under /chat/systemprompt
  • Register SystemPrompt handler in server initialization
internal/apiserver/database/model.go
internal/apiserver/database/mysql.go
internal/apiserver/database/postgres.go
internal/apiserver/database/sqlite.go
internal/apiserver/database/database.go
internal/apiserver/handler/systemprompt.go
cmd/apiserver/main.go

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@boston008 boston008 mentioned this pull request Jul 2, 2025
2 tasks done

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @boston008 - I've reviewed your changes - here's some feedback:

  • The LLMChatInterface component has grown very large—consider refactoring parts (like the SystemPrompt modal, auth token input, and message builders) into smaller subcomponents or custom hooks for clarity and maintainability.
  • You’ve duplicated logic for building availableTools lists and sanitizing tool names in multiple handlers—extract that into shared utility functions to DRY up the code.
  • The sanitizeToolName and getSanitizedToolNameMap helpers live inside the component; moving them to a standalone utils file will improve testability and separate concerns.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- The LLMChatInterface component has grown very large—consider refactoring parts (like the SystemPrompt modal, auth token input, and message builders) into smaller subcomponents or custom hooks for clarity and maintainability.
- You’ve duplicated logic for building availableTools lists and sanitizing tool names in multiple handlers—extract that into shared utility functions to DRY up the code.
- The sanitizeToolName and getSanitizedToolNameMap helpers live inside the component; moving them to a standalone utils file will improve testability and separate concerns.

## Individual Comments

### Comment 1
<location> `web/src/pages/chat/llm-chat-interface.tsx:320` </location>
<code_context>
         async (newToolCalls) => {
-          setMessages(prev => {
+          // Patch tool calls to always have originalName
+          const patchedToolCalls = newToolCalls.map((tc: any) => ({
+            ...tc,
+            function: {
</code_context>

<issue_to_address>
Avoid using 'any' for tool call typing.

Use the specific ToolCall type to improve type safety and maintainability.
</issue_to_address>

### Comment 2
<location> `web/src/pages/chat/llm-chat-interface.tsx:288` </location>
<code_context>
       };

-      setMessages(prev => [...prev, assistantMessage]);
+      setMessages((prev: Message[]) => [...prev, assistantMessage]);
       setIsGenerating(true);

</code_context>

<issue_to_address>
Consider deduplicating code for message streaming and tool call patching.

Extract the repeated logic into a helper function to improve maintainability and consistency.

Suggested implementation:

```typescript
      addStreamingAssistantMessage(setMessages);



// Helper function to add a streaming assistant message
function addStreamingAssistantMessage(setMessages: React.Dispatch<React.SetStateAction<Message[]>>) {
  const assistantMessage: Message = {
    id: uuidv4(),
    isStreaming: true
  };
  setMessages((prev: Message[]) => [...prev, assistantMessage]);
}

export function LLMChatInterface() {

```

- Replace any other repeated instances of adding a streaming assistant message (with the same structure) in this file with a call to `addStreamingAssistantMessage(setMessages)`.
- If tool call patching logic is also repeated, extract it similarly into a helper function and replace repeated code with calls to that function.
- Ensure the helper function is placed at an appropriate location in the file (e.g., above the component definition).
</issue_to_address>

### Comment 3
<location> `web/src/pages/chat/llm-chat-interface.tsx:605` </location>
<code_context>
+  }, []);
+
+  // Utility to sanitize tool names for VertexAI/Gemini
+  function sanitizeToolName(name: string): string {
+    // Only allow [a-zA-Z0-9_], must start with a letter or underscore
+    let sanitized = name.replace(/[^a-zA-Z0-9_]/g, '_');
+    if (!/^[a-zA-Z_]/.test(sanitized)) {
+      sanitized = '_' + sanitized;
+    }
+    return sanitized;
+  }
+
</code_context>

<issue_to_address>
Sanitization may cause name collisions for tools with similar names.

Names differing only by non-alphanumeric characters will be sanitized to the same value. Please implement a collision check or use a more robust mapping to prevent this.
</issue_to_address>

### Comment 4
<location> `web/src/pages/chat/llm-chat-interface.tsx:766` </location>
<code_context>
                   selectionMode="multiple"
                   selectedKeys={activeServices}
-                  onSelectionChange={(keys) => setActiveServices(Array.from(keys) as string[])}
+                  onSelectionChange={(keys: any) => setActiveServices(Array.from(keys) as string[])}
                   className="w-48"
                   size="sm"
</code_context>

<issue_to_address>
Avoid using 'any' for keys in onSelectionChange.

Specify the correct type for 'keys' to improve type safety.
</issue_to_address>

### Comment 5
<location> `web/src/pages/chat/llm-chat-interface.tsx:793` </location>
<code_context>
+            {isSystemPromptModalOpen && (
</code_context>

<issue_to_address>
System prompt modal does not handle save errors.

Currently, if saveSystemPrompt fails, the modal closes without notifying the user. Please add user feedback for save errors to enhance the user experience.
</issue_to_address>

### Comment 6
<location> `web/src/pages/chat/components/chat-message.tsx:37` </location>
<code_context>
     try {
-      if (!tool?.function?.name) {
+      // Use originalName if present, else fallback
+      const toolNameForParsing = (tool?.function as any)?.originalName || tool?.function?.name;
+      if (!toolNameForParsing) {
         toast.error(t('errors.invalid_tool_name'), {
</code_context>

<issue_to_address>
Using 'any' for tool.function reduces type safety.

Consider defining a type for tool.function that includes an optional originalName property to maintain type safety.
</issue_to_address>

<suggested_fix>
<<<<<<< SEARCH
      // Use originalName if present, else fallback
      const toolNameForParsing = (tool?.function as any)?.originalName || tool?.function?.name;
=======
      // Define a type for tool.function that includes optional originalName
      type ToolFunctionWithOriginalName = typeof tool.function & { originalName?: string };
      // Use originalName if present, else fallback
      const toolFunction = tool?.function as ToolFunctionWithOriginalName;
      const toolNameForParsing = toolFunction?.originalName || toolFunction?.name;
>>>>>>> REPLACE

</suggested_fix>

### Comment 7
<location> `web/src/pages/chat/components/chat-message.tsx:176` </location>
<code_context>
         )}
         {message.toolCalls?.filter(tool => tool?.function?.name).map((tool, index) => {
           const toolResult = findToolResult(tool.id);
+          const toolDisplayName = (tool.function as any).originalName || tool.function.name;
           return (
             <div key={index} className="mt-3 border border-blue-200 dark:border-blue-800 rounded-lg bg-blue-50/50 dark:bg-blue-950/20 overflow-hidden">
</code_context>

<issue_to_address>
Consider typing tool.function to avoid 'any' usage.

If tool.function may have an originalName property, update its type definition to include it for improved type safety.

Suggested implementation:

```typescript
        {message.toolCalls?.filter(tool => tool?.function?.name).map((tool, index) => {
          const toolResult = findToolResult(tool.id);
          const toolDisplayName = tool.function.originalName || tool.function.name;
          return (

```

You will also need to update the type definition for `tool.function` wherever it is defined (likely in a types or interfaces file). For example, if you have an interface like:

```ts
interface ToolFunction {
  name: string;
  // ...other properties
}
```

Update it to:

```ts
interface ToolFunction {
  name: string;
  originalName?: string;
  // ...other properties
}
```

And ensure that the type of `tool.function` is `ToolFunction`. If the type is defined inline or imported, update it accordingly.
</issue_to_address>

### Comment 8
<location> `web/src/services/mcp.ts:91` </location>
<code_context>
-      client.onerror = (error) => {
-        onError?.(error);
-        toast.error(t('errors.mcp_server_error', { server: serverName, error: error.message }), {
+      client.onerror = (error: unknown) => {
+        onError?.(error as Error);
+        toast.error(t('errors.mcp_server_error', { server: serverName, error: (error as Error).message }), {
           duration: 3000,
         });
</code_context>

<issue_to_address>
Casting error to Error may not always be safe.

Check if error is an instance of Error before accessing .message to avoid runtime issues.
</issue_to_address>

### Comment 9
<location> `web/src/services/mcp.ts:171` </location>
<code_context>
       };

+      // Prepare options for request
+      const options: any = this.lastEventIds.get(serverName)
+        ? { resumptionToken: this.lastEventIds.get(serverName) }
+        : {};
</code_context>

<issue_to_address>
Avoid using 'any' for options; define a proper type.

Consider creating a specific type for the options object to improve type safety when using client.request.
</issue_to_address>

<suggested_fix>
<<<<<<< SEARCH
      // Prepare options for request
      const options: any = this.lastEventIds.get(serverName)
        ? { resumptionToken: this.lastEventIds.get(serverName) }
        : {};
=======
      // Define a type for the options object
      type McpRequestOptions = {
        resumptionToken?: string;
      };

      // Prepare options for request
      const options: McpRequestOptions = this.lastEventIds.get(serverName)
        ? { resumptionToken: this.lastEventIds.get(serverName) }
        : {};
>>>>>>> REPLACE

</suggested_fix>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

async (newToolCalls) => {
setMessages(prev => {
// Patch tool calls to always have originalName
const patchedToolCalls = newToolCalls.map((tc: any) => ({

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Avoid using 'any' for tool call typing.

Use the specific ToolCall type to improve type safety and maintainability.

};

setMessages(prev => [...prev, assistantMessage]);
setMessages((prev: Message[]) => [...prev, assistantMessage]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Consider deduplicating code for message streaming and tool call patching.

Extract the repeated logic into a helper function to improve maintainability and consistency.

Suggested implementation:

      addStreamingAssistantMessage(setMessages);



// Helper function to add a streaming assistant message
function addStreamingAssistantMessage(setMessages: React.Dispatch<React.SetStateAction<Message[]>>) {
  const assistantMessage: Message = {
    id: uuidv4(),
    isStreaming: true
  };
  setMessages((prev: Message[]) => [...prev, assistantMessage]);
}

export function LLMChatInterface() {
  • Replace any other repeated instances of adding a streaming assistant message (with the same structure) in this file with a call to addStreamingAssistantMessage(setMessages).
  • If tool call patching logic is also repeated, extract it similarly into a helper function and replace repeated code with calls to that function.
  • Ensure the helper function is placed at an appropriate location in the file (e.g., above the component definition).

Comment on lines +605 to +611
function sanitizeToolName(name: string): string {
// Only allow [a-zA-Z0-9_], must start with a letter or underscore
let sanitized = name.replace(/[^a-zA-Z0-9_]/g, '_');
if (!/^[a-zA-Z_]/.test(sanitized)) {
sanitized = '_' + sanitized;
}
return sanitized;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (bug_risk): Sanitization may cause name collisions for tools with similar names.

Names differing only by non-alphanumeric characters will be sanitized to the same value. Please implement a collision check or use a more robust mapping to prevent this.

selectionMode="multiple"
selectedKeys={activeServices}
onSelectionChange={(keys) => setActiveServices(Array.from(keys) as string[])}
onSelectionChange={(keys: any) => setActiveServices(Array.from(keys) as string[])}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Avoid using 'any' for keys in onSelectionChange.

Specify the correct type for 'keys' to improve type safety.

@@ -647,19 +709,65 @@ export function LLMChatInterface() {
))}
</Select>
)}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: System prompt modal does not handle save errors.

Currently, if saveSystemPrompt fails, the modal closes without notifying the user. Please add user feedback for save errors to enhance the user experience.

Comment on lines +36 to +37
// Use originalName if present, else fallback
const toolNameForParsing = (tool?.function as any)?.originalName || tool?.function?.name;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Using 'any' for tool.function reduces type safety.

Consider defining a type for tool.function that includes an optional originalName property to maintain type safety.

Suggested change
// Use originalName if present, else fallback
const toolNameForParsing = (tool?.function as any)?.originalName || tool?.function?.name;
// Define a type for tool.function that includes optional originalName
type ToolFunctionWithOriginalName = typeof tool.function & { originalName?: string };
// Use originalName if present, else fallback
const toolFunction = tool?.function as ToolFunctionWithOriginalName;
const toolNameForParsing = toolFunction?.originalName || toolFunction?.name;

)}
{message.toolCalls?.filter(tool => tool?.function?.name).map((tool, index) => {
const toolResult = findToolResult(tool.id);
const toolDisplayName = (tool.function as any).originalName || tool.function.name;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Consider typing tool.function to avoid 'any' usage.

If tool.function may have an originalName property, update its type definition to include it for improved type safety.

Suggested implementation:

        {message.toolCalls?.filter(tool => tool?.function?.name).map((tool, index) => {
          const toolResult = findToolResult(tool.id);
          const toolDisplayName = tool.function.originalName || tool.function.name;
          return (

You will also need to update the type definition for tool.function wherever it is defined (likely in a types or interfaces file). For example, if you have an interface like:

interface ToolFunction {
  name: string;
  // ...other properties
}

Update it to:

interface ToolFunction {
  name: string;
  originalName?: string;
  // ...other properties
}

And ensure that the type of tool.function is ToolFunction. If the type is defined inline or imported, update it accordingly.

Comment thread web/src/services/mcp.ts
Comment on lines +91 to +93
client.onerror = (error: unknown) => {
onError?.(error as Error);
toast.error(t('errors.mcp_server_error', { server: serverName, error: (error as Error).message }), {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (bug_risk): Casting error to Error may not always be safe.

Check if error is an instance of Error before accessing .message to avoid runtime issues.

Comment thread web/src/services/mcp.ts
Comment on lines +170 to +173
// Prepare options for request
const options: any = this.lastEventIds.get(serverName)
? { resumptionToken: this.lastEventIds.get(serverName) }
: {};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Avoid using 'any' for options; define a proper type.

Consider creating a specific type for the options object to improve type safety when using client.request.

Suggested change
// Prepare options for request
const options: any = this.lastEventIds.get(serverName)
? { resumptionToken: this.lastEventIds.get(serverName) }
: {};
// Define a type for the options object
type McpRequestOptions = {
resumptionToken?: string;
};
// Prepare options for request
const options: McpRequestOptions = this.lastEventIds.get(serverName)
? { resumptionToken: this.lastEventIds.get(serverName) }
: {};

fix the import sequence of gateway and toast
@boston008

Copy link
Copy Markdown
Contributor Author

Order of import has been updated to fix the web tests and lint tsdk

@KamToHung KamToHung left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please verify your codes as copilot suggestions.

@iFurySt iFurySt left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM! Thanks!

@iFurySt
iFurySt merged commit ba9e02b into AmoyLab:main Jul 9, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants