<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Daiki Yamashita (FLECT) on Medium]]></title>
        <description><![CDATA[Stories by Daiki Yamashita (FLECT) on Medium]]></description>
        <link>https://medium.com/@daiki.yamashita_67366?source=rss-c1b6d182e72b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xvuEmX_8dvWwPJGnl004kg.png</url>
            <title>Stories by Daiki Yamashita (FLECT) on Medium</title>
            <link>https://medium.com/@daiki.yamashita_67366?source=rss-c1b6d182e72b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 07:08:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@daiki.yamashita_67366/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Understanding the Correct Way to Integrate Salesforce × Slack]]></title>
            <link>https://medium.com/@daiki.yamashita_67366/understanding-the-correct-way-to-integrate-salesforce-slack-c8d03d21bac6?source=rss-c1b6d182e72b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8d03d21bac6</guid>
            <category><![CDATA[salesforce]]></category>
            <category><![CDATA[slack]]></category>
            <dc:creator><![CDATA[Daiki Yamashita (FLECT)]]></dc:creator>
            <pubDate>Thu, 23 Jul 2026 01:51:26 GMT</pubDate>
            <atom:updated>2026-07-23T01:51:26.862Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*13cIQ2MXr2mSGtKvLUcmww.png" /></figure><p><strong>This is an English translation of the following original blog in Japanese:</strong></p><p><a href="https://cloud.flect.co.jp/entry/2026/07/14/110000">https://cloud.flect.co.jp/entry/2026/07/14/110000</a></p><p>Due to historical reasons, there are multiple generations of Salesforce–Slack integration methods coexisting, which makes it very hard to tell which approach is the current, correct one. Also, the configurations for the legacy methods are left on the UI without any warning, so even an extremely simple use case like “post a message from Salesforce to Slack” ends up requiring a surprisingly painful amount of technical decision-making.</p><p>On top of that, the official documentation contains no clear statement of “this is the latest approach.” So, to arrive at the correct implementation, you have to unravel the historical background piece by piece and figure out which configuration corresponds to which era’s method. Needless to say, this is a waste of time.</p><p>So this article summarizes the current state of Salesforce–Slack integration. But we limit its scope to the following two use cases:</p><ul><li>Sending a message from Salesforce to Slack</li><li>Displaying a preview of a Salesforce record in Slack</li></ul><p>These are the areas where the most confusion tends to arise, and if you get these right, there should be few practical problems otherwise.</p><h3><strong>TL;DR</strong></h3><p>For those short on time, here’s the conclusion up front.</p><h4><strong>Sending a message from Salesforce to Slack</strong></h4><p>The correct approach is to use a Slack app named “[Product] for Slack.” There are several variants, but if you just want to send messages, any of them will do:</p><ul><li><a href="https://slack.com/marketplace/A028VJ1KG3G-sales-cloud-for-slack">Sales Cloud for Slack</a></li><li><a href="https://slack.com/marketplace/A01RDL2NJAH-service-cloud-for-slack">Service Cloud for Slack</a></li><li><a href="https://slack.com/marketplace/A04HWE26PGT-prm-for-slack">PRM for Slack</a></li><li><a href="https://slack.com/marketplace/A02FTH353M0-crm-analytics">CRM Analytics for Slack</a></li></ul><p>Pick whichever you like, install it in Slack, and follow the steps in this documentation to connect Slack and Salesforce:</p><p><a href="https://slack.com/help/articles/30754346665747-Connect-Salesforce-and-Slack">Connect Salesforce and Slack</a></p><p>This makes the <a href="https://help.salesforce.com/s/articleView?id=platform.flow_ref_elements_actions_slack_send_message_to_slack_channel.htm&amp;type=5">Send Slack Message</a> action available from Flow, letting you send messages via the app. Sending messages requires adding the app to the relevant Slack channel, so don’t forget that step.</p><p>Note that this action is only available in Salesforce Flow, so if you want to send messages from Apex, you’ll need a workaround such as using Platform Events.</p><h4><strong>Displaying a preview of a Salesforce record in Slack</strong></h4><p>After completing the Slack–Salesforce connection described above, the record preview feature becomes available for that Salesforce org. Each individual user then needs to log in to Salesforce from Slack once before previews will actually appear for them.</p><p>Specifically, when a Salesforce record URL is included in a Slack message, it’s automatically recognized and a preview is displayed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zGq5dstyfxJHeoJs.png" /></figure><p>The preview display format can be changed via Slack-side configurations, though this requires administrator privileges. The method is described here:</p><p><a href="https://slack.com/help/articles/32665140498195-Set-up-and-manage-Salesforce-channels-in-Slack#manage-record-previews">Set up and manage Salesforce channels in Slack</a></p><p>Also, if the preview is set to Show record details, the fields of the record included in the preview can be controlled on the Salesforce side, per object, via a configuration called Slack Record Layout. The steps are here:</p><p><a href="https://help.salesforce.com/s/articleView?id=slack.slack_apps_digital_hq_unfurl_record_layout.htm&amp;type=5">Salesforce Help</a></p><p>(This document is filed under Salesforce for Slack, which is the name of the legacy method described later, but Slack Record Layout works with the current method)</p><p>Note also that the Slack preview is generated using the Salesforce profile of the user who posted the message, and the content is shared visibly with all other channel members, so you need to be careful with sensitive information, as described in the following document.</p><p><a href="https://slack.com/help/articles/32675871067283-Security-for-Salesforce-channels">Security for Salesforce channels</a></p><p>Therefore, if there are fields that shouldn’t be casually shared, you need to either disable detailed display on the Slack side, or exclude those fields from the preview display configurations for the relevant object on the Salesforce side.</p><h3><strong>The options and history behind Salesforce × Slack integration</strong></h3><p>I’ve introduced the recommended approach for each use case above, but there are other integration options. As far as we’re aware, the full set of integration methods is:</p><ol><li>Apex SDK for Slack</li><li>Salesforce Automations (Salesforce for Slack)</li><li>Connecting Salesforce from Slack</li><li>Sales Cloud for Slack / Service Cloud for Slack, etc.</li></ol><p>As already mentioned, the correct path is to choose 3 and 4; the others are legacy or otherwise problematic to adopt. In short, option 1 is a feature whose updates have stalled, making it hard to justify adopting, and option 2 is a legacy method that has given way to 3 and 4.</p><p>Laid out this way it may not look like there are enough options to cause confusion, but in practice it’s quite a struggle. This is mainly due to:</p><ul><li>The documentation doesn’t state which is current and which is legacy</li><li>It’s hard to tell what the current replacement is for each legacy method</li></ul><p>The first point is basically routine for anyone familiar with Salesforce, so it’s not a huge problem. Fortunately, the Slack apps used in the legacy method are clearly labeled “Legacy,” making it relatively easy to tell them apart. ~~Why doesn’t Salesforce do so?~~</p><p>The bigger issue is the second point: once you realize a given method is legacy, it’s hard to tell how to achieve the same thing using the current method. This is because the feature composition differs subtly between the legacy and current methods, so simply switching to the successor app doesn’t resolve everything on its own.</p><p>In other words, understanding the relationship between option 2 and options 3/4 is the key point, and this article focuses mainly on that. So option 1, which is a bit of a side note, will only get a brief overview.</p><h4><strong>Apex SDK for Slack</strong></h4><p><a href="https://developer.salesforce.com/docs/platform/salesforce-slack-sdk/guide/overview.html">Salesforce Developers</a></p><p>Apex SDK for Slack is an SDK for developing Slack apps in Apex, letting you control a Slack app from the Salesforce side to post messages and so on.</p><p>It’s structured like a direct port of the Slack SDK to Apex, giving you control over nearly all Slack app functionality, making it the most fine-grained option among those listed above.</p><p>However, Apex SDK for Slack is currently in Beta. And even though it isn’t legacy, which might make it seem promising for the future, this SDK has actually sat untouched for a long time since its Beta release. Specifically, the <a href="https://developer.salesforce.com/docs/platform/salesforce-slack-sdk/guide/changelog.html">documentation’s changelog</a> hasn’t been updated since July 2023, nearly three years of neglect.</p><p>So it’s questionable whether this will ever reach general availability, and adopting it carries real risk. For technical decision-making purposes, it’s safer to exclude it from consideration.</p><h4><strong>Salesforce Automations (Salesforce for Slack)</strong></h4><p><a href="https://slack.com/marketplace/A03269G3DNE-salesforce-automations-legacy">Salesforce Automations (Legacy)</a></p><p>Because the name “Salesforce for Slack” is catchy, it tends to show up quickly when searching for Salesforce × Slack integration methods. But as already mentioned, it’s a legacy approach. In this method, you install a Slack app called Salesforce Automations to achieve message sending and so on.</p><p>“Salesforce for Slack” is the app’s former name, later renamed to Salesforce Automations. However, Salesforce continues to refer to this integration method as Salesforce for Slack, creating a confusing situation where both names appear across the app and documentation. To avoid confusion, this article will consistently use “Salesforce Automations.”</p><p>Salesforce Automations broadly has two functions:</p><ol><li>Posting messages and notifications to Slack</li><li>Displaying previews of Salesforce records in Slack</li></ol><p>These are its main roles. However, since both can be replaced by newer methods, there’s no longer any reason to adopt Salesforce Automations going forward.</p><p>New installations are technically still possible at the time of writing, but since there’s no telling when it will be deprecated, it’s safer to exclude it from consideration barring special circumstances.</p><h4><strong>Replacing Salesforce Automations’ features with the current methods</strong></h4><p>As Salesforce Automations gave way to its successors, the feature composition changed slightly, which is the point most likely to cause confusion during technical decision-making.</p><p>Specifically, in the successor, the two functions mentioned above are distributed as follows:</p><ol><li>Posting messages and notifications to Slack<br>-&gt; Inherited by successor Slack apps such as Sales Cloud for Slack</li><li>Displaying previews of Salesforce records in Slack<br>-&gt;<strong> Automatically enabled once Slack and Salesforce are connected and authenticated</strong></li></ol><p>In other words, the preview display feature has been migrated to a native feature that’s automatically applied once each user logs in to Salesforce from Slack, and is no longer the app’s responsibility. As a result, successor apps like Sales Cloud for Slack do not include a preview display feature.</p><p>While it’s now more convenient in that no app installation is needed for previews, this is also a somewhat confusing change, since simply installing a successor app like Sales Cloud for Slack won’t by itself make previews appear.</p><p>One more thing worth flagging: Salesforce has an element that can mislead people into thinking “the successor Slack apps also have a preview feature.” That’s the following configuration under Salesforce’s Setup &gt; Slack Apps Setup:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Tw_TD3fvtOiqzn-2.png" /></figure><p>This screen has configurations for how Salesforce records are previewed in Slack, and its menu name “Slack App Setup” is extremely generic-sounding. So it seems like it would apply to the successor Slack apps too, but in fact it does not.</p><p><strong>Slack Apps Setup only affects Salesforce Automations, and has no effect whatsoever on the successor Slack apps.</strong> In short, it’s a configuration dedicated solely to the legacy method, so be careful not to confuse it with the configurations for the successor apps.</p><h4><strong>Connecting Salesforce from Slack</strong></h4><p><a href="https://slack.com/help/articles/30754346665747-Connect-Salesforce-and-Slack">Connect Salesforce and Slack</a></p><p>This is Slack’s native feature for connecting a Salesforce org to Slack. It’s the foundation of every current (non-legacy) integration method, and is a required step regardless of which approach you take. It’s also required when using any of the “[Product] for Slack” apps described later.</p><p>Making this connection enables the record preview feature for the org. Once a user has logged in to Salesforce, any Salesforce record URL they include in a Slack message will automatically display a preview. So if preview display is your only goal, installing a Slack app is not necessary.</p><p>The preview content can be customized to some extent; that method is described in the <a href="#1283">TL;DR</a> section above, so refer to it if needed.</p><p>Beyond preview display, it seems this connection also enables things like Quick Actions that let you create Salesforce records from Slack, but there’s no consolidated documentation on exactly what functionality is available. It seems you just have to explore it by observing actual behavior.</p><h4><strong>Sales Cloud for Slack / Service Cloud for Slack, etc.</strong></h4><ul><li><a href="https://slack.com/marketplace/A028VJ1KG3G-sales-cloud-for-slack">Sales Cloud for Slack</a></li><li><a href="https://slack.com/marketplace/A01RDL2NJAH-service-cloud-for-slack">Service Cloud for Slack</a></li></ul><p>If you want to send messages or notifications from Salesforce to Slack, you use one of these “[Product] for Slack” named Slack apps.</p><p>Each app has its own dedicated menu in Salesforce Setup for configuration, and only these configurations apply to that particular “[Product] for Slack” app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WKlU1WxZLufo2VaE.png" /></figure><p>To reiterate: the configurations under Setup &gt; Slack Apps Setup are unrelated to this group of apps.</p><p>If you just want to send a message from Salesforce to Slack, basically any of these apps will work fine. The concrete steps are:</p><ol><li>Connect Slack and Salesforce (as described <a href="#c5ec">above</a>)</li><li>Add the “[Product] for Slack” app to the destination Slack channel</li><li>Execute the <a href="https://help.salesforce.com/s/articleView?id=platform.flow_ref_elements_actions_slack_send_message_to_slack_channel.htm&amp;type=5">Send Slack Message</a> action in a Salesforce Flow</li></ol><p>Note that the action used in step 3 is Flow-only. This action isn’t available in Apex, so if you want to send messages from Apex using this integration method, you’ll need to implement something like publishing a Platform Event from Apex to trigger a message-sending Flow.</p><p>Currently, the only ways to send a message to Slack directly from Apex are either using Apex SDK for Slack or calling the Slack API directly, so it would be great to see convenience improvements in this area in the future.</p><h3><strong>Summary</strong></h3><p>This article summarized how to integrate Salesforce × Slack. To recap:</p><ul><li>Sending a message from Salesforce to Slack:<br>-&gt; Use an “[Product] for Slack” app such as Sales Cloud for Slack</li><li>Displaying a preview of a Salesforce record in Slack:<br>-&gt; Automatically enabled once you connect the Salesforce org to Slack</li><li>Salesforce Automations (Salesforce for Slack) is legacy</li><li>Apex SDK for Slack’s future is uncertain, so it’s best to avoid adopting it</li></ul><p>Salesforce × Slack integration is chaotic due to its historical background, and the overall picture is very hard to grasp. Having various configurations scattered in various places under various names is one problem, but my honest feeling is that I at least wish the documentation itself had been properly maintained.</p><p>We hope the content of this article proves helpful to developers.</p><p>Thank you for reading to the end.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8d03d21bac6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using MCP Elicitation to collect additional information from the user]]></title>
            <link>https://medium.com/@daiki.yamashita_67366/using-mcp-elicitation-to-collect-additional-information-from-the-user-d5c599ecae77?source=rss-c1b6d182e72b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5c599ecae77</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[mcp-server]]></category>
            <dc:creator><![CDATA[Daiki Yamashita (FLECT)]]></dc:creator>
            <pubDate>Tue, 26 Aug 2025 05:08:23 GMT</pubDate>
            <atom:updated>2025-08-26T05:08:23.493Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nmH0UV4gjKVWyuiw3kB8ZQ.png" /></figure><p><strong>This is an English translation of the following original blog in Japanese:</strong></p><p><a href="https://cloud.flect.co.jp/entry/2025/08/14/110000">https://cloud.flect.co.jp/entry/2025/08/14/110000</a></p><p>Salesforce announced <a href="https://www.salesforce.com/news/press-releases/2025/06/23/agentforce-3-announcement/">Agentforce 3</a>, and one of its headline features is the enhancement of connectivity with MCP. Not only will it enable feature extensions for AI Agents using MCP, but it also mentions the introduction of prebuilt MCPs tailored for various industries and AgentExchange, where you can discover third‑party MCPs, showing how much emphasis is being placed on this area. Meanwhile, on other platforms, MCP is becoming available from <a href="https://aws.amazon.com/jp/blogs/machine-learning/harness-the-power-of-mcp-servers-with-amazon-bedrock-agents/">Amazon Bedrock Agents</a> as well, so you can feel MCP’s usage gradually expanding.</p><p>Amid this growing momentum around MCP, the <a href="https://modelcontextprotocol.io/specification/2025-06-18">latest version</a> of the MCP specification was released on June 18, 2025. It includes several noteworthy changes such as updates to security considerations and support for Structured Tool Output. In this post, we’d like to focus on a newly added feature in the latest spec called <a href="https://modelcontextprotocol.io/specification/2025-06-18/client/elicitation">Elicitation</a>.</p><p>Elicitation is a capability that allows an MCP Server to issue a request to the user to gather additional information. Put simply, it enables MCP to ask follow‑up questions to the user.</p><p>While most of the other changes are essentially refinements to the existing spec, Elicitation alone introduces a new possibility for bidirectional interaction between LLMs and MCP, which is very interesting. Also, since the term “elicitation” evokes the same term used in the context of business analysis, we’re curious how far MCP aims to cover in that direction.</p><h3><strong>Overview</strong></h3><p>Elicitation is a feature that allows an MCP Server to request additional input from the user. The following sequence diagram illustrates how it works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*NR9WBdv9JhRmLNhGCzpGZw.png" /></figure><p>The high‑level description is as follows.</p><ol><li>The Client sends a request to the Server to use an MCP capability</li><li>The Server sends an Elicitation request to the Client</li><li>The Client displays a UI for additional input based on the contents of the Elicitation request</li><li>The user enters additional information using the input UI</li><li>The Client sends an Elicitation response to the Server</li><li>The Server sends a response for the MCP capability back to the Client</li></ol><p>In short, when an MCP capability request is received, the MCP Server can ask the user for additional input as needed; once the input is provided, it continues processing and returns an answer. In the sequence diagram above, item 1 calls an MCP Tool, but there’s no restriction on the target. You can also call a Resource or a Prompt.</p><p>The schema for parameters that require additional input is specified in the Elicitation request using JSON like the following.</p><pre>{<br>  &quot;type&quot;: &quot;object&quot;,<br>  &quot;properties&quot;: {<br>    &quot;somethingString&quot;: {<br>      &quot;type&quot;: &quot;string&quot;,<br>      &quot;title&quot;: &quot;Something String&quot;,<br>      &quot;description&quot;: &quot;Something string&quot;<br>    },<br>    &quot;somethingNumber&quot;: {<br>      &quot;type&quot;: &quot;number&quot;,<br>      &quot;title&quot;: &quot;Something Number&quot;,<br>      &quot;description&quot;: &quot;Something number&quot;<br>    }<br>  },<br>  &quot;required&quot;: [&quot;somethingString&quot;]<br>}</pre><p>Enums, maximum/minimum values, and more are supported, making input parameter specification quite flexible. For more details about the schema, see the MCP spec <a href="https://modelcontextprotocol.io/specification/2025-06-18/client/elicitation#request-schema">here</a>.</p><p>In the context of business analysis, “elicitation” is a fairly weighty concept, meaning questions aimed at drawing out necessary demands and requirements for a system. From the overview, however, at least in the current MCP, Elicitation doesn’t seem that grand; it feels more like a straightforward request for additional input.</p><h3><strong>Implementing Elicitation</strong></h3><p>To see Elicitation in action, let’s implement a sample that uses it. The MCP TypeScript SDK already provides a function to implement Elicitation, so we’ll use it this time.</p><p>We’ll implement a simple MCP Server with an echo function, except that the string to echo is obtained from Elicitation rather than as an input parameter.</p><pre>import { McpServer } from &quot;@modelcontextprotocol/sdk/server/mcp.js&quot;<br>import { StdioServerTransport } from &quot;@modelcontextprotocol/sdk/server/stdio.js&quot;<br><br><br>const server = new McpServer({<br>  name: &quot;demo-server&quot;,<br>  version: &quot;1.0.0&quot;<br>})<br><br>server.registerTool(&quot;echo&quot;,<br>  {<br>    title: &quot;Echo with elicitation&quot;,<br>    description: &quot;Echo the input&quot;,<br>    inputSchema: {}<br>  },<br>  async ({}) =&gt; {<br>    const result = await server.server.elicitInput({<br>      message: &quot;Please input something string:&quot;,<br>      requestedSchema: {<br>        type: &quot;object&quot;,<br>        properties: {<br>          input: {<br>            type: &quot;string&quot;,<br>            title: &quot;Input&quot;,<br>            description: &quot;Please input something string:&quot;<br>          }<br>        },<br>        required: [&quot;input&quot;]<br>      }<br>    })<br><br>    if (result?.action !== &quot;accept&quot; || typeof(result?.content?.input) !== &quot;string&quot;) {<br>      console.log(result)<br>      return {<br>        content: [{ type: &quot;text&quot;, text: &quot;Invalid input&quot; }]<br>      }<br>    }<br><br>    return {<br>      content: [{ type: &quot;text&quot;, text: result.content?.input }]<br>    }<br>  }<br>)<br><br>const transport = new StdioServerTransport()<br>await server.connect(transport)</pre><p>The part that actually performs Elicitation is where elicitInput() is called. By calling this function, you can execute the entire Elicitation flow. Nice and simple.</p><p>Let’s run it. Start the above MCP Server and execute the Echo tool in MCP Inspector. An additional input form like the following will appear:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ALtG9-oYh2qfL0XBR9NXag.png" /></figure><p>Enter an arbitrary string and click Submit, and the tool’s execution result will be displayed. The following shows the screen when the additional input is the string &quot;Hello, World!”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pBBi1qdPjKesI7xA7oaf1g.png" /></figure><p>Looks good. It’s easy to implement and the behavior is straightforward, so no complaints here.</p><h3><strong>Constraints</strong></h3><p>Now that we have a rough idea of how Elicitation works, let’s dig a bit deeper into the finer details.</p><p>As we’ve seen, Elicitation is a very simple feature, but there are a few important constraints. The tricky part is that, being a young feature, many of these constraints are not explicitly documented in the spec or the MCP SDK docs. As it stands, developers have to verify behavior themselves and build their own understanding.</p><p>In the hope of saving fellow developers some effort, we’ll list the constraints of Elicitation that we noticed while actually experimenting.</p><h4><strong>Timeouts occur while waiting for Elicitation input</strong></h4><p>To recap the Elicitation flow:</p><ol><li>The Client sends a request to the Server to use an MCP capability</li><li>The Server sends an Elicitation request to the Client</li><li>The Client sends an Elicitation response to the Server</li><li>The Server sends a response for the MCP capability back to the Client</li></ol><p>Elicitation requests are sent over a path like Server-Sent Events (SSE), and run in parallel with the MCP capability-use request. The MCP capability-use request is not terminated or suspended when using Elicitation; it simply withholds sending its response until the Elicitation completes.</p><p>You may have guessed the fatal structural flaw here. While the MCP capability-use request waits for the Elicitation to complete, the Client-side timeout counter continues to tick. Consequently, if the additional input via Elicitation takes too long, the MCP capability-use request will time out.</p><p>The diagram looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*5cdu3tSBkAIuQ7vb245mVA.png" /></figure><p>This is one of the most delicate aspects of Elicitation’s design. It makes you want to set a more generous timeout for MCP capability-use requests, but there’s fundamentally nothing you can do; an MCP Server has no way to influence the MCP Client’s timeout configuration. And from the MCP Client’s perspective, it doesn’t know which server capabilities will use Elicitation, so there’s nothing it can do either.</p><p>There’s no good solution to this constraint at the moment, so the frank impression is that we should simply wait for the spec to be refined a bit more.</p><h4><strong>Session management is required for use over Streamable HTTP</strong></h4><p>The earlier Echo MCP implementation used StdioServerTransport for standard I/O, but Elicitation can of course be implemented over Streamable HTTP as well. However, when using Elicitation over Streamable HTTP, session management is required.</p><p>This constraint arises because Streamable HTTP uses SSE to conduct Elicitation exchanges. Specifically, with Streamable HTTP, Elicitation proceeds as follows:</p><ol><li>The Client sends a GET request to the Server to establish the SSE channel</li><li>The Client sends a POST request to the Server to use an MCP capability</li><li>The Server sends an Elicitation request to the Client over the SSE channel from step 1</li><li>The Client sends the Elicitation response to the Server over the same SSE channel from step 1</li><li>The Server sends the MCP capability response back to the Client</li></ol><p>In other words, to perform Elicitation you need to associate the two HTTP requests from steps 1 and 2, which necessitates session management.</p><p>For reference, here is the Echo MCP implemented with Streamable HTTP:</p><pre>import express from &quot;express&quot;<br>import { randomUUID } from &quot;node:crypto&quot;<br>import { McpServer } from &quot;@modelcontextprotocol/sdk/server/mcp.js&quot;<br>import { StreamableHTTPServerTransport } from &quot;@modelcontextprotocol/sdk/server/streamableHttp.js&quot;<br>import { isInitializeRequest } from &quot;@modelcontextprotocol/sdk/types.js&quot;<br><br><br>const server = new McpServer({<br>  name: &quot;demo-server&quot;,<br>  version: &quot;1.0.0&quot;<br>})<br><br>server.registerTool(&quot;echo&quot;,<br>  {<br>    title: &quot;Echo with elicitation&quot;,<br>    description: &quot;Echo the input&quot;,<br>    inputSchema: {}<br>  },<br>  async ({}) =&gt; {<br>    const result = await server.server.elicitInput({<br>      message: &quot;Please input something string:&quot;,<br>      requestedSchema: {<br>        type: &quot;object&quot;,<br>        properties: {<br>          input: {<br>            type: &quot;string&quot;,<br>            title: &quot;Input&quot;,<br>            description: &quot;Please input something string:&quot;<br>          }<br>        },<br>        required: [&quot;input&quot;]<br>      }<br>    })<br><br>    if (result?.action !== &quot;accept&quot; || typeof(result?.content?.input) !== &quot;string&quot;) {<br>      console.log(result)<br>      return {<br>        content: [{ type: &quot;text&quot;, text: &quot;Invalid input&quot; }]<br>      }<br>    }<br><br>    return {<br>      content: [{ type: &quot;text&quot;, text: result.content?.input }]<br>    }<br>  }<br>)<br><br><br>const app = express()<br>app.use(express.json())<br><br>const transports: { [sessionId: string]: StreamableHTTPServerTransport } = {}<br><br>const buildInvalidRequestResponse = () =&gt; {<br>  return {<br>    jsonrpc: &#39;2.0&#39;,<br>    error: {<br>      code: -32000,<br>      message: &#39;Bad Request: No valid session ID provided&#39;,<br>    },<br>    id: null,<br>  }<br>}<br><br>app.post(&#39;/mcp&#39;, async (req, res) =&gt; {<br>  const sessionId = req.headers[&#39;mcp-session-id&#39;] as string | undefined<br>  let transport: StreamableHTTPServerTransport<br><br>  if (sessionId &amp;&amp; transports[sessionId]) {<br>    transport = transports[sessionId]<br>  } else if (!sessionId &amp;&amp; isInitializeRequest(req.body)) {<br>    transport = new StreamableHTTPServerTransport({<br>      sessionIdGenerator: () =&gt; randomUUID(),<br>      onsessioninitialized: (sessionId) =&gt; {<br>        transports[sessionId] = transport<br>      },<br>    })<br>    transport.onclose = () =&gt; {<br>      if (transport.sessionId) {<br>        delete transports[transport.sessionId]<br>      }<br>    }<br>    await server.connect(transport)<br>  } else {<br>    res.status(400).json(buildInvalidRequestResponse())<br>    return<br>  }<br><br>  await transport.handleRequest(req, res, req.body)<br>})<br><br>const handleSessionRequest = async (req: express.Request, res: express.Response) =&gt; {<br>  const sessionId = req.headers[&#39;mcp-session-id&#39;] as string | undefined<br>  if (!sessionId || !transports[sessionId]) {<br>    res.status(400).send(&#39;Invalid or missing session ID&#39;)<br>    return<br>  }<br><br>  const transport = transports[sessionId]<br>  await transport.handleRequest(req, res)<br>}<br><br>app.get(&#39;/mcp&#39;, handleSessionRequest)<br><br>app.delete(&#39;/mcp&#39;, handleSessionRequest)<br><br>app.listen(3001)</pre><p>Note that this session-management constraint is documented neither in the MCP spec nor in the SDK docs. To make matters worse, if you implement Elicitation over Streamable HTTP without session management, the MCP TypeScript SDK doesn’t throw any explicit error; it simply times out, making it hard to infer the correct behavior from runtime symptoms.</p><p>This is a trap that’s easy to fall into when using Streamable HTTP, so watch out.</p><h4><strong>Multiple Elicitations are not supported</strong></h4><p>At present, it seems you cannot issue multiple Elicitation requests within a single MCP capability-use request.</p><p>The spec doesn’t state anything about the number of requests, and the Elicitation <a href="https://github.com/modelcontextprotocol/modelcontextprotocol/pull/382">PR</a> includes comments that seem to allow multiple requests, so there’s a slight mismatch. However, testing with the MCP TypeScript SDK didn’t work, so we’re listing this as a constraint. Specifically, it appears that the second Elicitation request is stuck without being sent, causing the MCP capability-use request to time out. Maybe it’s a bug in the current version of the SDK.</p><p>Because of this constraint, you can’t ask the user multiple questions. For example, for an MCP that calculates the area of a shape, you can’t first ask for the shape type (circle, rectangle, etc.) and then ask for the shape’s properties (circle radius or rectangle width/height).</p><p>In such cases, you’ll likely have two options; either ask for the shape type via the input parameters of the MCP capability-use request, or ask for both the shape type and properties all at once, like below.</p><pre>const result = await server.server.elicitInput({<br>  message: &quot;Please input the type of shape and the properties&quot;,<br>  requestedSchema: {<br>    type: &quot;object&quot;,<br>    properties: {<br>      type: {<br>        type: &quot;string&quot;,<br>        title: &quot;Type&quot;,<br>        description: &quot;Please choose a type of shape&quot;,<br>        enum: [&quot;circle&quot;, &quot;rectangle&quot;],<br>        enumNames: [&quot;Circle&quot;, &quot;Rectangle&quot;]<br>      },<br>      radius: {<br>        type: &quot;number&quot;,<br>        title: &quot;Radius&quot;,<br>        description: &quot;Please input the radius of the circle. This parameter is required when the type is circle.&quot;<br>      },<br>      width: {<br>        type: &quot;number&quot;,<br>        title: &quot;Width&quot;,<br>        description: &quot;Please input the width of the rectangle. This parameter is required when the type is rectangle.&quot;<br>      },<br>      height: {<br>        type: &quot;number&quot;,<br>        title: &quot;Height&quot;,<br>        description: &quot;Please input the height of the rectangle. This parameter is required when the type is rectangle.&quot;<br>      },<br>    },<br>    required: [&quot;type&quot;]<br>  }<br>})</pre><p>Asking everything at once like this can hurt input-field clarity and complicate validation, so it seems suitable only for limited scenarios.</p><h4><strong>Do not exchange sensitive information</strong></h4><p>The spec explicitly states that sensitive information must not be exchanged via Elicitation.</p><p>This is, needless to say, a security-driven constraint. Information obtained via MCP features, including Elicitation, may always be copied into an LLM’s context by the Client, and such security violations are often hard to prevent merely by deprecating them in the protocol spec. Hence the decision to avoid handling sensitive information in the first place.</p><p>You can see the discussion about this point in the Elicitation <a href="https://github.com/modelcontextprotocol/modelcontextprotocol/pull/382">PR</a>.</p><h3><strong>What Use Cases Is It Suited For?</strong></h3><p>While it does leave the impression of having more constraints than expected, Elicitation still brings genuinely new possibilities. It’s worth understanding in which use cases we can expect it to shine.</p><p>The Elicitation <a href="https://github.com/modelcontextprotocol/modelcontextprotocol/pull/382">PR</a> lists the following five use cases, which could serve as helpful hints:</p><ol><li>Confirmation of critical actions</li><li>Redirecting user to a sign-in flow</li><li>Clarification of ambiguous requests</li><li>Progressive form filling</li><li>Contextual information gathering</li></ol><p>However, these were envisioned at the time the PR was created, and some clearly no longer align with the released Elicitation spec.</p><p>Below, we’ll examine whether each of these use cases fits the post-release Elicitation spec.</p><h4><strong>1. Confirmation of critical actions</strong></h4><p>The first example is confirming important actions. Think of asking “Are you sure you want to delete this?” before deleting a file from storage like S3.</p><p>This looks promising. Tools that could act as an MCP Client, such as AI editors like Cursor, often include a feature to obtain user approval for actions executed via MCP. While this might seem to overlap with this use case, those features are often applied uniformly to all actions, and for day-to-day work, users tend to set them to auto-approve to reduce friction. In that scenario, adding Elicitation as an extra confirmation step only for particularly important actions seems reasonable.</p><p>What’s also nice is that this use case doesn’t seem to be less susceptible to the constraints mentioned above.</p><h4><strong>2. Redirecting user to a sign-in flow</strong></h4><p>The second, guiding the user into an authentication flow, is clearly infeasible under the Elicitation spec at release.</p><p>Elicitation cannot handle sensitive information to begin with, which rules out credentials for various authentication schemes, as well as tokens obtained as a result of authentication. It’s extremely hard to play any supplementary role in auth flows while adhering to this rule. We recommend using the MCP’s OAuth-related specifications from the start instead.</p><p>This use case appears to be a holdover from when handling sensitive information via Elicitation was allowed. Once that was prohibited due to security concerns, the feasibility of this use case effectively vanished.</p><h4><strong>3. Clarification of ambiguous requests</strong></h4><p>Third is asking follow-up questions to clarify an ambiguous request.</p><p>A design that leaves ambiguity at the request stage is problematic in itself, so this use case seems a bit questionable. That said, there are situations where Elicitation is beneficial:</p><ol><li>When the user’s choices are determined dynamically</li><li>When additional information is required only in certain situations</li></ol><p>For example, suppose you’re developing an MCP to book meeting rooms. You could design it so that “the user specifies the room and time as input parameters to make a reservation,” but then the user has to check in advance which rooms are available at which times. Instead, it may be friendlier to accept looser input like “I want a reservation within this time range,” and use Elicitation to return a list of available rooms and times as an enum. That’s case 1: when choices change depending on resource availability, Elicitation is valuable.</p><p>Also, suppose a particular meeting room is subdivided, and when reserving it the user must specify which section to use. In this case, adding a follow-up question via Elicitation is a natural implementation. That’s case 2.</p><p>In practice, case 1 is likely the more common use. In case 2, relying heavily on Elicitation risks complicating the logic, so we need to find the right balance.</p><h4><strong>4. Progressive form filling</strong></h4><p>This refers to multi-turn input across several steps. When there are many input parameters, asking for everything at once can harm UX, so staged input could be beneficial.</p><p>However, in our testing, multiple Elicitation cycles didn’t work at all. Currently, you can only collect additional information once. Under these circumstances, it’s hard to expect much reduction in input burden.</p><p>Also, beyond reducing input load, it’s unclear what other benefits staged input provides. Until multiple Elicitation rounds are supported, this one can probably stay on the back burner.</p><h4><strong>5. Contextual information gathering</strong></h4><p>The last item is contextual information gathering, but it’s too abstract to picture clearly. It feels more like a “miscellaneous” category than a concrete scenario.</p><h4><strong>Other</strong></h4><p>The <a href="https://github.com/modelcontextprotocol/typescript-sdk">MCP TypeScript SDK</a> includes a reservation system MCP as an example of Elicitation. There, when a reservation fails under the specified conditions, Elicitation is used to prompt the user to input alternative dates.</p><p>This is essentially using Elicitation for exception handling, which seems tricky to apply. Whether the user wants to propose alternatives after a failed reservation likely depends on the situation, so simply stating that the reservation failed is also a valid approach. It’s a use case you can adopt only when the next step after a failed request is obvious, so it doesn’t seem broadly applicable.</p><p>Summing up, promising use cases appear to be:</p><ul><li>Approvals for executing critical actions</li><li>Presenting candidate options in resource booking and similar flows</li><li>Collecting additional information only under specific, limited conditions</li></ul><h3><strong>Conclusion</strong></h3><p>That wraps up this overview of MCP’s Elicitation.</p><p>We expect consultative follow-up questions by LLMs to play an important role in future workflows, which is why Elicitation caught our eye. However, since MCP tends to target more static concerns, it felt a bit different from what we’d hoped.</p><p>Even so, it undoubtedly has the potential to unlock interesting possibilities, and we’re looking forward to future developments. It’s a bit awkward to use right now, but hopefully upcoming revisions will smooth things out.</p><p>That’s all. Thank you for reading to the end.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5c599ecae77" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monitoring Data Cloud Credit Consumption with Flow]]></title>
            <link>https://medium.com/@daiki.yamashita_67366/monitoring-data-cloud-credit-consumption-with-flow-a8c9240d0faf?source=rss-c1b6d182e72b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8c9240d0faf</guid>
            <category><![CDATA[salesforce]]></category>
            <category><![CDATA[data-cloud-in-salesforce]]></category>
            <dc:creator><![CDATA[Daiki Yamashita (FLECT)]]></dc:creator>
            <pubDate>Thu, 05 Jun 2025 05:38:37 GMT</pubDate>
            <atom:updated>2025-06-05T05:38:37.284Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L31mWJ0dhHrjobsEXIebYg.png" /></figure><p><strong>This is an English translation of the following original blog in Japanese:</strong></p><p><a href="https://cloud.flect.co.jp/entry/2025/05/29/100000">https://cloud.flect.co.jp/entry/2025/05/29/100000</a></p><p>Data Cloud provides several DLOs (Data Lake Objects) for managing credit consumption, but Salesforce’s official documentation does not explain what the fields in these DLOs mean. Therefore, when you actually try to monitor credit consumption, you end up with the mysterious task of staring at real records and inferring the meaning of each field yourself.</p><p>Obviously, the less time we spend on this kind of soul-crushing work, the better. So in this post we’ll share the knowledge we gained by analyzing actual DLO records and show you how to build Flows that monitor credit consumption.</p><h3><strong>Overview</strong></h3><p>We will build the following two Flows:</p><ol><li>A Flow that monitors fluctuations in credit consumption.</li><li>A Flow that watches for low remaining credits.</li></ol><p>Flow 1 runs daily and checks whether the current day’s credit consumption deviates greatly from the average over the past X days. Flow 2 runs hourly and checks whether total consumed credits have reached X % of the credit limit. In both Flows, an email notification is sent to a designated recipient when an anomaly is detected.</p><p>Data Cloud credits are tracked by a category called Cards. In Flow 1 we look at total daily credit consumption regardless of Card, while in Flow 2 we calculate the consumption ratio per Card. Because the remaining balance is determined per Card, Flow 2 must be Card-based; Flow 1 could also be aggregated per Card, but to keep the explanation straightforward we aggregate the entire amount into a single total.</p><h3><strong>Adding DLOs to a Data Space</strong></h3><p>The DLOs for managing credit consumption are not included in the data space by default; you must add them manually. Follow <a href="https://help.salesforce.com/s/articleView?id=xcloud.wallet_view_dlos.htm&amp;type=5">the official documentation</a> and add the following three DLOs:</p><ul><li>TenantDailyEntitlementConsumption</li><li>TenantHourlyEntitlementConsumption</li><li>TenantEntitlementTransaction</li></ul><p>As their names imply, the first two store daily and hourly credit-consumption data, while TenantEntitlementTransaction stores transaction records. The field definitions are a bit tricky; we’ll cover them later.</p><p>After adding the DLOs, create corresponding DMOs and set up mappings. A Flow can reference only DMOs, so don’t skip this step.</p><h3><strong>Creating the Flow to Monitor Credit-Consumption Fluctuations</strong></h3><p>Let’s start with Flow 1. This Flow checks whether today’s credit consumption deviates significantly from the average of the past X days.</p><p>Because we need daily information, we will use TenantDailyEntitlementConsumption. Note that multiple records will be created per Card each day, rather than a single record.</p><p>If we can identify which field in this DLO represents credit consumption, the implementation is easy. Exploring the fields, we find these four:</p><ul><li>Unit</li><li>Unit Consumed</li><li>Multiplier</li><li>Raw Usage</li></ul><p>None of the names are very intuitive, but we must figure out how to calculate credit consumption from them.</p><h4><strong>How Credit Consumption Is Calculated</strong></h4><p>The clue lies in this Trailhead module:</p><p><a href="https://trailhead.salesforce.com/ja/content/learn/modules/data-cloud-credit-consumption-quick-look/get-started-with-data-cloud-credit-consumption">Data Cloud Credit Consumption Insights and Strategies</a></p><p>It explains:</p><blockquote>Each usage type has a unit and multiplier. The unit represents how much data is considered 1 unit of usage. This is 1 million for every usage type. For Data Cloud, the multiplier represents how many credits are consumed by 1 unit of usage. Multiply this number by your usage to get the total credits consumed. Refer to the rate card linked in the Resources section for current multipliers. To calculate how many credits are consumed in a usage event, you need to know the usage type, the multiplier for the usage type, and how much data was processed.</blockquote><blockquote>d represents the total amount of data processed. m represents the multiplier for the usage type.</blockquote><blockquote>Credits consumed = (d/1,000,000) * m</blockquote><p>In short, the data amount relevant for billing is aggregated in units defined by Unit, and the credits consumed are calculated by multiplying that aggregation by Multiplier. For example, if the data being aggregated is API calls, Unit is 1,000, and Multiplier is 3, then every 1,000 API calls consume 3 credits.</p><p>In TenantDailyEntitlementConsumption, the data amount subject to billing (API calls in the above example) is stored in Raw Usage, so:</p><pre>Credits Consumed = (Raw Usage / Unit) * Multiplier</pre><p>Although the Trailhead says Unit is always 1,000,000, we’ve observed other values in real data, so beware! W̶h̶y̶ ̶w̶o̶u̶l̶d̶ ̶t̶h̶e̶y̶ ̶l̶i̶e̶?̶</p><p>You might think we’re done, but there’s an easier way: the field Unit Consumed actually stores the credit consumption itself. We noticed this while examining records. A snippet of real data shows that when you calculate according to the formula above, the result matches Unit Consumed exactly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-kT4o-5_BAmlV2yitMaaFw.png" /></figure><p>Therefore, to obtain credit consumption, just reference Unit Consumed. Yay.</p><h4><strong>Implementing the Flow</strong></h4><p>All that’s left is to implement. The Flow looks like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*ZJkxPV1ugqKd84mmXFS5TQ.png" /></figure><p>Although it seems complex, it’s straightforward:</p><ol><li>Build it as a Schedule-Triggered Flow to run daily.</li><li>Schedule-Triggered Flows must invoke a Wait element before any callouts, and DMO queries count as callouts. So add an initial Wait. <a href="https://help.salesforce.com/s/articleView?language=en_US&amp;id=platform.flow_considerations_trigger_schedule.htm&amp;type=5">The official documentation</a> suggests using $Flow.CurrentDateTime to minimize the wait time. If you find it troublesome to set it up, you can just wait for one minute.</li><li>Query past X days of TenantDailyEntitlementConsumption by the Drawdown Day field. You can compute “X days ago” with a formula.</li><li>Loop through those records and calculate the average daily credit consumption by using Unit Consumed. Because each day has multiple records, divide by X, not by record count.</li><li>Query today’s TenantDailyEntitlementConsumption using Drawdown Day.</li><li>Loop through today’s records and sum Unit Consumed to get today’s total.</li><li>Multiply the average from step 4 by a threshold factor (e.g., 1.25 and for +25 %) and compare. If today’s total exceeds the threshold, send an email. You can likewise detect abnormally low consumption if needed.</li></ol><p>Once you understand the DLO fields, it’s easy.</p><h3><strong>Creating the Flow to Watch for Low Remaining Credits</strong></h3><p>Next, Flow 2 checks hourly whether total consumed credits for each Card have reached X % of the limit.</p><p>To know what fraction of a Card’s credits are consumed, we need two pieces of information: (a) the total credits consumed for that Card, and (b) the credit limit. We’ll use the other two DLOs introduced earlier.</p><h4><strong>Total Credits Consumed</strong></h4><p>TenantHourlyEntitlementConsumption contains Unit Consumed, so summing this over the license term would give total consumption. But there’s an easier way: the field Card Definition Balance stores the remaining credits for that Card. You can get total credit consumed by combining this balance with the credit limit:</p><pre>Credits Consumed = Credit Limit - Credit Balance</pre><p>Because this field becomes negative value if the consumption exceeds 100 %, the calculation still works in the case. Nice.</p><h4><strong>Credit Limit</strong></h4><p>Use TenantEntitlementTransaction. This DLO stores all credit transactions, grants and consumptions.</p><p>The credit limit is the total credits granted by Salesforce (e.g., through license purchase). So filter TenantEntitlementTransaction where Transaction Type = Add and sum the Quantity field. We validated that this matches the “Total Credits” displayed in Data Cloud Consumption Cards.</p><p>TenantEntitlementTransaction also has Entitlement Card Definition Dev Name, which stores the Card type. Therefore, to get the credit limit for a specific Card, filter on both Transaction Type = Add and Entitlement Card Definition Dev Name = the Card type of the trigger record.</p><h4><strong>Implementing the Flow</strong></h4><p>Here’s the Flow outline:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*nV06PsYLqAqJAZRaBntknw.png" /></figure><ol><li>Implement as a Data Cloud-Triggered Flow that fires when a TenantHourlyEntitlementConsumption record is created. This gives easy access to the credit balance and Card type.</li><li>Query TenantEntitlementTransaction with these criteria:<br>- Transaction Type = Add<br>- Entitlement Card Definition Dev Name equals Card Definition Developer Name of the trigger record</li><li>Loop through the results to sum Quantity and compute the credit limit. Also calculate total consumed credits using a formula.</li><li>Compute the consumption ratio and branch: send email when it reaches 50 % and 100 %.</li></ol><p>Again, once you know the DLO field meanings, nothing is difficult.</p><h3>Conclusion</h3><p>We built Flows to monitor Data Cloud credit consumption.</p><p>Because the credit model is fairly complex, monitoring usage is important. Data Cloud is relatively new, and some behaviors, like Data Cloud-Triggered Flows consuming credits via Data Actions, are hard to see from the user side. If credits run out, you’ll incur extra charges, so early detection of unexpected consumption is vital.</p><p>As always, we wish Salesforce’s developer documentation were better organized. We hope this article eases the burden for fellow developers.</p><p>Thank you for reading to the end.</p><h3><strong>Bonus: Mapping Card Types</strong></h3><p>The Card type strings stored in various DLOs (as Card Definition Developer Name) differ slightly from the names shown in Consumption Cards, making them hard to read. I cross-referenced them during implementation; here’s the mapping:</p><p>(The name of the Consumption Card is on the left side of the arrow and the Card Definition Developer Name is on the right side.)</p><ul><li>Conversations -&gt; DigitalEngagementConversation</li><li>Data Services Credits -&gt; PlatformServiceCard</li><li>Einstein Requests -&gt; EinsteinAI_Einstein1</li><li>Data Storage Allocation -&gt; DataStorageCard</li><li>Segmentations Activations -&gt; Personalization</li></ul><p>These mappings were verified by matching calculated total consumption and credit limits. However, our environment had no consumption for Segmentations Activations, so that row is inferred by elimination; We are less confident about it.</p><p>If you find any errors, please let us know. :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8c9240d0faf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implement user authentication functionality in the MCP server]]></title>
            <link>https://medium.com/@daiki.yamashita_67366/implement-user-authentication-functionality-in-the-mcp-server-9b241b4a18a6?source=rss-c1b6d182e72b------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b241b4a18a6</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[mcp-server]]></category>
            <dc:creator><![CDATA[Daiki Yamashita (FLECT)]]></dc:creator>
            <pubDate>Tue, 27 May 2025 06:17:29 GMT</pubDate>
            <atom:updated>2025-05-27T06:29:17.074Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x79raTYItU6r5JG1iinJpg.png" /></figure><p><strong>This is an English translation of the following original blog in Japanese:</strong></p><p><a href="https://cloud.flect.co.jp/entry/2025/05/07/100000">https://cloud.flect.co.jp/entry/2025/05/07/100000</a></p><p><a href="https://modelcontextprotocol.io/introduction">MCP</a>, defined by Anthropic to enable feature enhancements in LLMs, is attracting significant attention. By using MCP, developers can create additional features for LLMs without being dependent on individual models.</p><p>The initial specification of MCP was released on November 5, 2024, and the latest version was published on March 26, 2025, with updates that added descriptions for several features. In this article, we will focus on authentication functionality within MCP.</p><p>There are several use cases where proper access control is necessary for MCP, and one of the prominent ones is resource reference. For example, if you want an LLM to access files stored on a server, it’s natural to utilize file access permissions tied to user profiles. Considering this, it seems there is substantial demand for authentication in MCP.</p><p>In this article, we will explain the authentication methods currently available for MCP and their implementation.</p><h3>Background Knowledge</h3><p>Before delving into the authentication, it’s important to understand that MCP supports two execution modes: local and remote. Let’s briefly explain these modes.</p><p>However, the difference is simple: “local” refers to setting up the MCP server as a process on a local machine, while “remote” refers to hosting the MCP server as a remote server accessible via the Internet. In other words, the difference is whether MCP is used via the Internet or directly.</p><p>While “local execution” is typically associated with development and testing, in the context of MCP, local server deployment remains the mainstream approach. For example, GitHub’s <a href="https://github.com/github/github-mcp-server">MCP Server</a> is fairly well-known and assumes local execution.</p><h3>Authentication Before the Latest Specification</h3><p>Although details about authentication were added to the MCP specification on March 26, 2025, there were already MCP servers that required authentication beforehand. The aforementioned GitHub MCP Server is one such example. These MCP servers perform authentication by setting credentials in environment variables.</p><p>For instance, with GitHub MCP Server, you can authenticate by setting a Personal Access Token (PAT) in the GITHUB_PERSONAL_ACCESS_TOKEN environment variable.</p><pre>{<br>  &quot;mcp&quot;: {<br>    &quot;inputs&quot;: [{...}],<br>    &quot;servers&quot;: {<br>      &quot;github&quot;: {<br>        ...,<br>        &quot;env&quot;: {<br>          &quot;GITHUB_PERSONAL_ACCESS_TOKEN&quot;: &quot;...&quot;<br>        }<br>      }<br>    }<br>  }<br>}</pre><p>Since PAT contains user-specific permission information, functions can be executed with the user’s permissions. This approach can also be used with OAuth’s Client Credentials Flow.</p><p>While setting credentials in environment variables is a simple method, it has some drawbacks, as listed below:</p><ol><li>Not all IDPs support issuing a PAT, and most don’t. Without PAT support, the MCP can only rely on a single credential, making user-specific permission control impossible.</li><li>PATs are designed as tokens for individual use and are generally unsuitable for use as remote server credentials. Hence, when the MCP must be remote server, this approach cannot be used.</li></ol><h3>Authentication in the Latest Specification</h3><p>Acknowledging the challenges outlined above, MCP specifications were revised to explicitly align with OAuth 2.1. This is detailed in <a href="https://modelcontextprotocol.io/specification/2025-03-26/basic/authorization">here</a>.</p><p>The specification specifies compliance with the following authentication flow:</p><ul><li>Authorization Code Flow</li><li>Client Credentials Flow</li></ul><p>With explicit support for Authorization Code Flow, MCP servers can now demand user logins during operation, enabling functions tailored to individual users’ permissions. Compliance is specified with a “SHOULD” directive, meaning it is not mandatory but expected to be widely supported due to the critical nature of authentication functionality.</p><p>However, MCP has unique specifications that differ from typical OAuth implementations, requiring awareness of two key points:</p><ol><li>Requests for authentication return a 401 Unauthorized response.</li><li>Dynamic Client Registration (DCR) compliance is recommended.</li></ol><p>Understanding these differences ensures a smoother implementation. Let’s discuss them briefly.</p><h4>Authentication Requests Return 401 Unauthorized</h4><p>Typically in web contexts, when a resource server receives a request requiring OAuth authentication, it responds with 302 Found, prompting redirection. However, in MCP, authentication flows return 401 Unauthorized instead of 302 Found. This means redirection to provide authentication server URLs is not possible.</p><p>To address this, MCP server must conform to one of the following approaches:</p><ol><li>Provide the URL of the authentication server via OAuth 2.0 Authorization Server Metadata.</li><li>Provide an OAuth endpoint itself.</li></ol><p>In other words, the client calls the metadata retrieval endpoint, and if the response contains the URL of the authentication server, it makes an OAuth authentication request to that endpoint; if not, it makes an OAuth authentication request to the MCP server itself.</p><p>In the latter case, MCP servers also act as authentication servers. The MCP TypeScript SDK includes functions specifically designed to proxy OAuth endpoints through MCP servers. As a side note, the MCP Python SDK currently lacks authentication functionality, so be aware when choosing tools.</p><p>Endpoints for these scenarios are defined as follows:</p><ul><li>Authorization Server Metadata endpoint (for #1 above):<br>- /.well-known/oauth-authorization-server</li><li>OAuth endpoints (for #2 above):<br>- /authorize <br>- /token <br>- /register</li></ul><h4>Dynamic Client Registration (DCR) Compliance is Recommended</h4><p>In the context of using OAuth on the web, the common flow involves pre-registering the OAuth client beforehand and specifying the pre-registered client using the Client ID at the point of calling the authorization endpoint.</p><p>However, OAuth provides a mechanism called Dynamic Client Registration (DCR), which allows OAuth clients to be registered dynamically if pre-registration of OAuth clients does not suit the nature of the system.</p><p>MCP recommends compliance with DCR, and the recommended level is “SHOULD.” While non-compliance is technically an option, the <a href="https://github.com/modelcontextprotocol/inspector">MCP Inspector</a>, officially developed by MCP, terminates authentication against servers without DCR, suggesting strong emphasis on compliance.</p><p>That said, IDPs such as Microsoft Entra and Amazon Cognito currently don’t support DCR, which makes the current situation feel like the kind of chaos characteristic of transitional periods.</p><h3>Precautions for OAuth Compliance in MCP</h3><p>Some of you may have already noticed this, but <strong>MCP is stating compliance with OAuth 2.1, and OAuth 2.1 is currently a draft</strong>. In other words, the specification is still under development, and the currently published information is subject to change. You can check the ongoing draft specification <a href="https://oauth.net/2.1/">here</a>.</p><p>That said, among the changes introduced by OAuth 2.1 that are relevant to the Authorization Code Flow, only the following change is currently in place:</p><ul><li>The redirect_uri parameter is no longer required when calling the Token endpoint.</li></ul><p>The reasoning behind the removal of the redirect_uri is explained <a href="https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-12#name-redirect-uri-parameter-in-t">here</a>. In summary, it was originally introduced to prevent the theft of authorization codes. However, with PKCE becoming standard, this issue has been resolved, and redirect_uri is considered to have fulfilled its purpose and was subsequently removed.</p><p>In OAuth 2.0, specifying the redirect_uri is mandatory when calling the Token endpoint. Therefore, a client that complies only with OAuth 2.1 will fail to authenticate against an OAuth 2.0 server due to the absence of this required parameter. On the other hand, an OAuth 2.0 client, as long as PKCE is applied, can authenticate without issues on an OAuth 2.1 server.</p><p>Currently, since OAuth 2.1 is still in draft status, it is only natural that IDPs, such as various providers, are limited to supporting OAuth 2.0. As a result, if you wish to perform OAuth authentication using MCP at this point in time, the client must be implemented to conform to OAuth 2.0. MCP’s expression of compliance with the draft specification has led to a bit of confusion …</p><h3>Implementation Using MCP TypeScript SDK</h3><p>We know that authentication should work regardless of the OAuth version on the server side if the client complies with OAuth 2.0. The MCP TypeScript SDK already includes a set of implemented functions for authentication, so let’s try setting up an MCP server with authentication.</p><p>Since MCP itself does not have authentication functionality, you’ll need a separate IDP for testing. For this case, we’ll use Auth0 as the IDP. Auth0 supports DCR, which makes it well-suited for this test. Similarly, we’ll need an MCP client, and for this, we’ll use MCP Inspector. Just to be sure, we verified that MCP Inspector is OAuth 2.0 compliant and includes the redirect_uri parameter when calling the Token endpoint.</p><h4>Configuring Auth0</h4><p>Before coding, configure Auth0 for DCR. Enable the following settings under Settings &gt; Advanced within your Auth0 tenant:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q-u1iIgsu0YjCnh75mRtPw.png" /></figure><p>The first setting is used to enable DCR itself, while the second setting serves to automatically assign Auth0 Connections to clients created via DCR. If the second setting is not enabled, an error indicating “no connection exists” will occur, preventing authentication.</p><p>Additionally, clients created via DCR are treated as Third-Party clients. However, in Auth0, there is a restriction where Third-Party clients can only connect to Domain Level Connections. Therefore, you will need to configure the required Connections as Domain Level Connections according to the documentation outlined below.</p><p><a href="https://auth0.com/docs/authenticate/identity-providers/promote-connections-to-domain-level">Promote Connections to Domain Level</a></p><p>Simply call the “Update a Connection” API, setting is_domain_connection to true.</p><h4>Implementation Plan</h4><p>The environment setup is complete, so now it’s time to proceed with the implementation.</p><p>The README for the MCP TypeScript SDK on <a href="https://github.com/modelcontextprotocol/typescript-sdk">GitHub</a> kindly provides a sample implementation for proxying OAuth endpoints through MCP. As a result, if you naively try to implement authentication functionality, you might be tempted to use the functions provided for proxying OAuth endpoints based on that sample. However, this is a trap. These functions are implemented so poorly that their use is absolutely not recommended.</p><p>Specifically, there are the following a̶b̶s̶u̶r̶d̶ implementation restrictions:</p><ul><li>Parameters undefined in OAuth 2.1 are not passed to the proxy destination.</li></ul><p>In other words, the redirect_uri parameter is not passed to the Token endpoint, and authentication will only work with IDPs that strictly comply with an unextended version of OAuth 2.1. Naturally, such IDPs don’t exist as of now, meaning these functions are effectively useless.</p><p>Therefore, instead of relying on these unusable functions, we will proceed with an implementation approach that uses MCP’s metadata to provide the URL of the Auth0 authentication endpoint.</p><h4>Implementation</h4><p>There is virtually no documentation for the authentication function of the MCP SDK, so the only way to implement it is to read the SDK source code, which can be full of troubles.</p><p>After investigating, it seems that a function called metadataHandler has been provided for offering metadata in MCP. Therefore, this time, we will make use of it.</p><pre>import express, { Request, Response, RequestHandler } from &quot;express&quot;<br>import { McpServer } from &quot;@modelcontextprotocol/sdk/server/mcp.js&quot;<br>import { SSEServerTransport } from &quot;@modelcontextprotocol/sdk/server/sse.js&quot;<br>import { InvalidTokenError, ServerError } from &#39;@modelcontextprotocol/sdk/server/auth/errors.js&#39;<br>import { metadataHandler } from &#39;@modelcontextprotocol/sdk/server/auth/handlers/metadata.js&#39;<br>import { z } from &quot;zod&quot;<br><br><br>const ISSUER = &quot;https://your-tenant.jp.auth0.com/&quot;<br><br><br>// MCP Server<br><br>const server = new McpServer({<br>  name: &quot;Test MCP Server&quot;,<br>  version: &quot;1.0.0&quot;,<br>})<br><br>server.tool(&quot;add&quot;,<br>  { a: z.number(), b: z.number() },<br>  async ({ a, b }) =&gt; ({<br>    content: [{ type: &quot;text&quot;, text: String(a + b) }]<br>  })<br>)<br><br><br>// Auth Settings<br><br>const mcpMetadataRouter = (): RequestHandler =&gt; {<br>  const router = express.Router()<br><br>  router.use(&quot;/.well-known/oauth-authorization-server&quot;, metadataHandler({<br>    issuer: ISSUER,<br><br>    authorization_endpoint: new URL(&quot;/authorize&quot;, ISSUER).href,<br>    token_endpoint: new URL(&quot;/oauth/token&quot;, ISSUER).href,<br>    registration_endpoint: new URL(&quot;/oidc/register&quot;, ISSUER).href,<br><br>    response_types_supported: [&quot;code&quot;],<br>    code_challenge_methods_supported: [&quot;S256&quot;],<br><br>    token_endpoint_auth_methods_supported: [&quot;client_secret_post&quot;],<br>    grant_types_supported: [&quot;authorization_code&quot;, &quot;refresh_token&quot;],<br>  }))<br><br>  return router<br>}<br><br>const requireAuth = (): RequestHandler =&gt; {<br>  return async (req, res, next) =&gt; {<br>    try {<br>      const header = req.headers.authorization;<br>      if (!header) {<br>        throw new InvalidTokenError(&quot;Missing Authorization header&quot;);<br>      }<br><br>      const [type, token] = header.split(&#39; &#39;);<br>      if (type.toLowerCase() !== &#39;bearer&#39; || !token) {<br>        throw new InvalidTokenError(&quot;Invalid Authorization header format, expected &#39;Bearer TOKEN&#39;&quot;);<br>      }<br><br>      // TODO: add validation here if you need to verify access token<br><br>      next()<br><br>    } catch (error) {<br>      if (error instanceof InvalidTokenError) {<br>        res.set(&quot;WWW-Authenticate&quot;, `Bearer error=&quot;${error.errorCode}&quot;, error_description=&quot;${error.message}&quot;`);<br>        res.status(401).json(error.toResponseObject());<br>      } else {<br>        console.error(&quot;Unexpected error authenticating bearer token:&quot;, error);<br>        res.status(500).json(new ServerError(&quot;Internal Server Error&quot;).toResponseObject())<br>      }<br>    }<br>  }<br>}<br><br>const transports: {[sessionId: string]: SSEServerTransport} = {}<br><br>const app = express()<br><br>app.use(mcpMetadataRouter())<br><br>app.get(&quot;/sse&quot;, requireAuth(), async (_: Request, res: Response) =&gt; {<br>  const transport = new SSEServerTransport(&#39;/messages&#39;, res)<br>  transports[transport.sessionId] = transport<br>  res.on(&quot;close&quot;, () =&gt; {<br>    delete transports[transport.sessionId]<br>  })<br>  await server.connect(transport)<br>})<br><br>app.post(&quot;/messages&quot;, requireAuth(), async (req: Request, res: Response) =&gt; {<br>  const sessionId = req.query.sessionId as string<br>  const transport = transports[sessionId]<br>  if (transport) {<br>    await transport.handlePostMessage(req, res)<br>  } else {<br>    res.status(400).send(&#39;No transport found for sessionId&#39;)<br>  }<br>})<br><br>app.listen(3001)<br>console.log(&#39;Server is running on port 3001&#39;)</pre><p>Using mcpMetadataRouter, we provide Authorization Server Metadata endpoint that supplies the URL of the Auth0 authentication endpoint. This allows MCP clients to know the authentication destination.</p><p>In the code above, token validation is not performed, and only a TODO comment is left behind. This is due to restrictions associated with Auth0’s tokens. Specifically, if the audience parameter is not included when calling /authorize, Auth0 returns an opaque token, which makes it impossible to validate the token on the resource server side. In this case, since MCP Inspector is the client, we were unable to instruct it to include additional parameters, so we had to give up on validation. However, if the audience parameter is included, a JWT is returned as the token, which can be validated without issue.</p><p>The authentication functions of the MCP SDK feel somewhat immature in terms of both implementation and documentation. It took considerable time to arrive at the above implementation and successfully enable authentication in MCP. We hope this implementation will be helpful to others.</p><h3>Conclusion</h3><p>To summarize, here are the key points:</p><ul><li>MCP authentication methods are as follows:<br>- Provisioning credentials via environment variables.<br>- Authentication using OAuth 2.1.</li><li>MCP’s OAuth slightly differs from typical one on web.<br>- Authentication servers are determined via Authorization Server Metadata rather than redirects.<br>- DCR compliance is recommended for IDPs.</li><li>MCP SDKs are immature and require considerable effort.<br>- Avoid using the SDK’s OAuth proxy functions.</li></ul><p>We expect that implementing MCP authentication would be easy, but in reality, it turned out to be quite challenging to implement. While it’s unclear why much of the difficulties stemmed from the quality of MCP’s official SDK, we believe these issues will be resolved as the infrastructure matures. L̶e̶t̶’̶s̶ ̶h̶o̶p̶e̶ ̶i̶t̶ ̶g̶e̶t̶s̶ ̶w̶e̶e̶d̶e̶d̶ ̶o̶u̶t̶.̶</p><p>That said, there’s no doubt that there is a demand for providing authentication functionality within MCP, so it feels reassuring to have established a method for achieving this relatively early. I hope this article serves as a helpful resource to ease the burden on other engineers tackling similar challenges.</p><p>Thank you for reading to the end.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b241b4a18a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Providing Custom UX Services with Agentforce Service Agent]]></title>
            <link>https://medium.com/@daiki.yamashita_67366/providing-custom-ux-services-with-agentforce-service-agent-8d0be8db760f?source=rss-c1b6d182e72b------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d0be8db760f</guid>
            <category><![CDATA[agentforce]]></category>
            <category><![CDATA[salesforce]]></category>
            <dc:creator><![CDATA[Daiki Yamashita (FLECT)]]></dc:creator>
            <pubDate>Wed, 12 Mar 2025 02:09:54 GMT</pubDate>
            <atom:updated>2025-03-12T02:09:54.844Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>This is English translation of the following original blog in Japanese:</strong></p><p><a href="https://cloud.flect.co.jp/entry/2025/03/05/171034">https://cloud.flect.co.jp/entry/2025/03/05/171034</a></p><p>Salesforce’s recent quarterly earnings report announced that the number of Agentforce implementations has exceeded 5,000, highlighting the growing trend of Salesforce utilizing LLMs. In this article, we would like to talk about Service Agent, one of the core features of Agentforce.</p><p>There are many possible use cases for Agentforce Service Agent, but a typical example is a personalized advisor for individuals. It functions like a digital secretary or a consultant providing tailored support based on the user’s context. Regardless of the type the service type, delivering UX customized to individual users is increasingly in high demand.</p><p>Building such a service requires user authentication, and authenticated users’ data must be accessible to the Service Agent. Salesforce indeed offers a mechanism for this, though it’s provided not by the Service Agent itself, but by Omni-Channel — the component responsible for exposing the agent to the internet.</p><p>As mentioned in <a href="https://medium.com/@daiki.yamashita_67366/accessing-agentforce-service-agent-from-external-web-pages-1976a8904b97">the previous articles</a>, although these two services are closely related, their documentation is fragmented, making it cumbersome to locate relevant information, forcing us to search through various documentation sources.</p><p>Therefore, it would be worthwhile to give the compiled information here. In this article, we explain how to integrate user authentication with Service Agent and provide a corresponding custom UX.</p><p>Note that this article doesn’t cover how to expose Service Agent through API, as <a href="https://medium.com/@daiki.yamashita_67366/accessing-agentforce-service-agent-from-external-web-pages-1976a8904b97">the previous articles</a> has already addressed this topic. Therefore, we assume that you have already created the necessary Omni-channel resources to do that.</p><h3><strong>Overview</strong></h3><p>Earlier, we mentioned that Omni-channel supports user authentication. It is actually a JWT verification using JWKS. Note that this is a verification of JWTs signed by an authentication server elsewhere, meaning Omni-channel doesn’t authenticate users by itself. Therefore, using this feature requires a separate authentication server.</p><p>The JWT verification by JWKS in Omni-channel works as follows:</p><ol><li>The user logs into the authentication server.</li><li>The authentication server returns a JWT as an access token.</li><li>The user calls the Omni-channel API to generate an access token using the JWT.</li><li>Omni-channel retrieves the JWKS from the authentication server.</li><li>Omni-channel verifies the JWT using the JWKS.</li><li>Omni-channel returns an access token to the user if the verification is successful.</li></ol><p>Overall, Omni-Channel approves this flow if it successfully verifies the JWT issued by an authentication server using the JWKS provided by that server. <a href="https://help.salesforce.com/s/articleView?id=service.user_verification_overview.htm&amp;type=5">The official documentation</a> provides a detailed description of the process above. The process is straightforward and JWTs are protected by asymmetric key encryption, making it secure.</p><p>You can use any authentication server as long as it supports JWT and JWKS. In this article, we use a Salesforce Connected App for authentication and arrange it with Omni-channel.</p><p>The specific implementation steps are as follows:</p><ol><li>Create a Connected App that supports JWT.</li><li>Register the JWKS retrieval endpoint in Messaging for In-App and Web (MIAW).</li><li>Enable user verification in Messaging Settings.</li><li>Allow Service Agent to read information of authenticated users.</li></ol><p>The actual settings will be explained step by step below.</p><h3><strong>Create a Connected App that supports JWT</strong></h3><p>Since we need to use JWT as the access token, it is necessary to create a Connected App with appropriate settings as Salesforce will use an opaque token encoded with its unique method if not specified.</p><p>Create a Connected App and apply the following settings:</p><ul><li>Check the “Enable OAuth Settings” checkbox.</li><li>Add the following scopes to “Selected OAuth Scopes”:<br>- Access the identity URL service (id, profile, email, address, phone)<br>- Manage user data via APIs (api)<br>- Manage user data via Web browsers (web)<br>- Perform requests at any time (refresh_token, offline_access)</li><li>Check the “Issue JSON Web Token (JWT)-based access tokens for named users” checkbox.</li></ul><p>OAuth Scopes might appear unrelated to JWT settings at first glance, but they are indeed connected in a less obvious way. This is because <a href="https://help.salesforce.com/s/articleView?id=xcloud.jwt_access_tokens.htm&amp;type=5">the official documentation</a> mentions the following:</p><blockquote>Compared to opaque access tokens, JWT-based access tokens have different functionality and limitations. For example, JWT-based access tokens can be used only to access REST APIs.</blockquote><p>Due to these functional limitations specific for JWT-based access tokens, setting overly broad permissions in OAuth Scopes can result in runtime errors. Therefore we have explicitly listed the scopes we applied here.</p><p>After creating the Connected App, configure additional settings by selecting the app from Setup &gt; Manage Connected App. This screen is entirely different from the one used when initially creating the Connected App; certain settings cannot be configured from the initial screen. T̶h̶i̶s̶ ̶i̶s̶ ̶w̶e̶l̶l̶-̶k̶n̶o̶w̶n̶ ̶a̶s̶ ̶d̶a̶r̶k̶ ̶p̶a̶t̶t̶e̶r̶n̶ ̶U̶I̶ ̶i̶n̶ ̶t̶h̶e̶ ̶i̶n̶d̶u̶s̶t̶r̶y̶.̶</p><p>Check the “Issue JSON Web Token (JWT)-based access tokens” checkbox.</p><p>This completes the setup for the Connected App.</p><h3><strong>Register the JWKS retrieval endpoint in MIAW</strong></h3><p>Navigate to Setup &gt; Messaging for In-App and Web User Verification and register the JWKS endpoint. Since we are using Connected App, the JWKS endpoint will be Salesforce itself.</p><p>In the JSON Web Keysets section, press “New” to display the following popup and enter the necessary information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i3JPkIUN7EQijJal1pSfoQ.png" /></figure><p>JWKS can be retrieved from id/keys endpoint in Salesforce.</p><h3><strong>Enable user verification in Messaging Settings</strong></h3><p>As the final step of user authentication configuration, enable user verification in the relevant channel in Setup &gt; Messaging Settings. <strong>From the dropdown next to the channel name on the list, select “Edit.”</strong> Please note that the settings below cannot be configured from the screen that opens after selecting the channel name from the list. D̶a̶r̶k̶ ̶p̶a̶t̶t̶e̶r̶n̶ ̶U̶I̶ ̶a̶g̶a̶i̶n̶.̶</p><p>Check the “Add User Verification” checkbox to enable it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OZss9vZIUV-NlB44m44ZBw.png" /></figure><p>Once the above setting is saved, select the relevant channel name from the list and proceed to the details screen. Here too, there are items that cannot be configured from the screen opened by selecting “Edit” from the list. A̶g̶a̶i̶n̶?̶</p><p>If “Add User Verification” is enabled, “User Verification Configuration” will be shown at the bottom of the screen. Press “New” and add setting. <strong>Note that this item cannot be deleted once created.</strong> It can be disabled later, so there is no functional issue, but the item will remain in the list. :D</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_oGihd7sKNaZAkEpubqYwQ.png" /></figure><p>Select the JSON Web Keysets created in the previous section in the Keyset field.</p><h3><strong>Testing the User Verification</strong></h3><p>At this point, as you should have now completed configuring user authentication. You can test the user verification for MIAW. Let’s verify that user authentication is correctly required.</p><p>MIAW has two APIs for issuing access tokens: one for authenticated users with JWT verification function, <a href="https://developer.salesforce.com/docs/service/messaging-api/references/miaw-api-reference?meta=generateAccessTokenForAuthenticatedUser">generateAccessTokenForAuthenticatedUser</a>, and one for unauthenticated guest users, <a href="https://developer.salesforce.com/docs/service/messaging-api/references/miaw-api-reference?meta=generateAccessTokenForUnauthenticatedUser">generateAccessTokenForUnauthenticatedUser</a>. We will confirm that the former succeeds and the latter fails.</p><p>First, let’s confirm that the authenticated user API succeeds. Any method can be used to obtain a JWT as long as it works, but to make this demo realistic, we will use the Authorization Code Flow, which involves the Salesforce login screen.</p><p>Let’s write a test script in Python.</p><pre>from dotenv import load_dotenv<br>load_dotenv(override=True)<br><br>import os<br>import requests<br>import urllib.parse as urlparse<br>import webbrowser<br>from http.server import BaseHTTPRequestHandler, HTTPServer<br><br><br>SF_INSTANCE_URL = os.environ[&#39;SF_INSTANCE_URL&#39;]<br>SF_CLIENT_ID = os.environ[&#39;SF_CLIENT_ID&#39;]<br>SF_CLIENT_SECRET = os.environ[&#39;SF_CLIENT_SECRET&#39;]<br><br>SF_MIAW_ORG_ID = os.environ[&#39;SF_MIAW_ORG_ID&#39;]<br>SF_MIAW_DEV_NAME = os.environ[&#39;SF_MIAW_DEV_NAME&#39;]<br>SF_MIAW_URL = os.environ[&#39;SF_MIAW_URL&#39;]<br><br><br>CODE_CHALLENGE = &#39;ASf42cqjec0s_0XwM1E7HROSkJCLxztVX7wtFLkoAOo&#39;<br>CODE_VERIFIER = &#39;f3YW2kiXRiw6YdczpZNr3MwWGjTER2nnY0gN2HJ90ODmoWOoAonufVu81BWnJfhvanIYlDnYw8XsLiPgPVmlx8tJVjj6KpC79n94biNvX95ESVdkZYaKk_zCW_5gaWs0&#39;<br>REDIRECT_URL = &#39;http://localhost:8080/callback&#39;<br><br><br>def retrieve_jwt(code):<br>    res = requests.post(<br>        f&#39;{SF_INSTANCE_URL}/services/oauth2/token&#39;,<br>        data={<br>            &#39;grant_type&#39;: &#39;authorization_code&#39;,<br>            &#39;code&#39;: code,<br>            &#39;client_id&#39;: SF_CLIENT_ID,<br>            &#39;client_secret&#39;: SF_CLIENT_SECRET,<br>            &#39;redirect_uri&#39;: REDIRECT_URL,<br>            &#39;code_verifier&#39;: CODE_VERIFIER,<br>        }<br>    )<br>    print(res.status_code)<br>    print(res.text)<br>    return res.json()[&#39;access_token&#39;]<br><br><br>def retrieve_authed_user_miaw_token(jwt):<br>    res = requests.post(<br>        f&#39;{SF_MIAW_URL}/iamessage/api/v2/authorization/authenticated/access-token&#39;,<br>        headers={<br>            &#39;Content-Type&#39;: &#39;application/json&#39;,<br>        },<br>        json={<br>            &#39;orgId&#39;: SF_MIAW_ORG_ID,<br>            &#39;esDeveloperName&#39;: SF_MIAW_DEV_NAME,<br>            &#39;capabilitiesVersion&#39;: &#39;1&#39;,<br>            &#39;platform&#39;: &#39;Web&#39;,<br>            &#39;authorizationType&#39;: &#39;JWT&#39;,<br>            &#39;customerIdentityToken&#39;: jwt,<br>        },<br>    )<br>    print(res.status_code)<br>    print(res.text)<br>    return res.json()[&#39;accessToken&#39;]<br><br><br># Create a simple HTTP server to handle the callback<br>class AuthenticationCodeHandler(BaseHTTPRequestHandler):<br>    def do_GET(self):<br>        self.send_response(200)<br>        self.end_headers()<br><br>        parsed = urlparse.urlparse(self.path)<br>        params = urlparse.parse_qs(parsed.query)<br><br>        code = params.get(&#39;code&#39;, [None])[0]<br>        if code:<br>            jwt = retrieve_jwt(code)<br>            token = retrieve_authed_user_miaw_token(jwt)<br>            self.wfile.write(f&#39;Authentication successful. Token: {token}&#39;.encode())<br>        else:<br>            self.wfile.write(b&#39;Failed to retrieve JWT.&#39;)<br><br><br>if __name__ == &#39;__main__&#39;:<br>    endpoint = f&#39;{SF_INSTANCE_URL}/services/oauth2/authorize&#39;<br>    params = {<br>        &#39;response_type&#39;: &#39;code&#39;,<br>        &#39;client_id&#39;: SF_CLIENT_ID,<br>        &#39;redirect_uri&#39;: REDIRECT_URL,<br>        &#39;scope&#39;: &#39;api&#39;,<br>        &#39;code_challenge&#39;: &#39;ASf42cqjec0s_0XwM1E7HROSkJCLxztVX7wtFLkoAOo&#39;,<br>        &#39;code_challenge_method&#39;: &#39;S256&#39;,<br>    }<br>    url = f&#39;{endpoint}?{urlparse.urlencode(params)}&#39;<br>    webbrowser.open(url)<br><br>    httpd = HTTPServer((&#39;localhost&#39;, 8080), AuthenticationCodeHandler)<br>    httpd.serve_forever()</pre><p>When you run this script, it will open the Salesforce login page in your browser. After authenticating, the JWT retrieved from Salesforce will be used to call the authenticated user API for MIAW to issue an access token with JWT verification.</p><p>If it succeeds, the following string will be displayed on the browser screen:</p><pre>Authentication successful. Token: {your-access-token}</pre><p>Let’s also verify the scenario involving the guest user API call. Since authentication is not required in this case, the test script can be relatively straightforward.</p><pre>if __name__ == &#39;__main__&#39;:<br>    res = requests.post(<br>        f&#39;{SF_MIAW_URL}/iamessage/api/v2/authorization/unauthenticated/access-token&#39;,<br>        headers={<br>            &#39;Content-Type&#39;: &#39;application/json&#39;,<br>        },<br>        json={<br>            &#39;orgId&#39;: SF_MIAW_ORG_ID,<br>            &#39;esDeveloperName&#39;: SF_MIAW_DEV_NAME,<br>            &#39;capabilitiesVersion&#39;: &#39;1&#39;,<br>            &#39;platform&#39;: &#39;Web&#39;,<br>        },<br>    )<br>    print(res.text)</pre><p>It properly results in an error. Well done.</p><h3><strong>Allow Service Agent to read information of authenticated users</strong></h3><p>Enabling JWT verification in MIAW brings an additional benefit: the authenticated user is registered in the MessagingEndUser at the start of a conversation with the Service Agent. The MessagingEndUser is an object that is related to the MessagingSession, which is provided as a context variable of the Service Agent.</p><p>Specifically, the MessagingEndUser.MessagingPlatformKey will contain the sub claim of the JWT in the following format:</p><pre>v2/iamessage/AUTH/{config-name}/uid:{sub}</pre><p>The config-name will be the name of the Configuration Name set in Messaging Settings. And the sub obtained by parsing this string is described in the <a href="https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.2">RFC</a> as:</p><blockquote>The “sub” (subject) claim identifies the principal that is the subject of the JWT.</blockquote><p>This means it will store information to uniquely identify the user. The specific information stored depends on the implementation, but in Salesforce JWT, the user ID is stored. By leveraging this, you can retrieve user data from the context and provide a custom UX.</p><p>Let’s proceed with the settings to reference MessagingEndUser from the Service Agent.</p><h4><strong>Configuring Permissions</strong></h4><p>The Einstein Agent profile applied to Service Agent users does not include access permissions to Standard Objects. Therefore, you must grant permissions to access MessagingEndUser in advance by using Permission Sets, etc.</p><p>Additionally, Agent Builder has settings that determine field-level access to MessagingSession for the Service Agent, so you need to check them as well. You can configure them in Agent Builder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*g2U0VotyhLZ4Vn7p-hkdhw.png" /></figure><p>MessagingEndUserId, which the Service Agent will reference this time, is included in MessagingSession by default, so no changes are needed. However, make sure to verify that the required fields are included in MessagingSession when you need to access additional fields.</p><h4><strong>Creating Actions</strong></h4><p>As we only need to verify that the Service Agent can reference MessagingSession.MessagingEndUserId here, directing the Service Agent to output the value of MessagingEndUserId seems like the simplest method. However, this approach doesn’t work because the Einstein Trust Layer forbids direct output of the ID. As a result, the Service Agent refuses to respond.</p><p>Therefore, we will use a roundabout method: prepare an Agent Action that accepts the MessagingEndUser’s ID as input, and confirm that the MessagingEndUserId content is specified in the input by checking the event log of this action. So we implemented an action that retrieves the MessagingEndUser record corresponding to the ID and returns the record summary. This action can be easily implemented in Flow as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-WfEpJO0fZoBzbxzUdvCgg.png" /></figure><p>It simply searches, formats the result by using Text Template, and outputs it. For reference, the output format is as follows:</p><pre>name: {!retrieve_messaging_user.Name}<br>id: {!retrieve_messaging_user.MessagingPlatformKey}</pre><p>Add the following instructions to the Topics for this action:</p><blockquote>When a user greets, use CustomUXTest action and pass the value of MessagingSession.MessagingEndUserId found in the context variable. And then, follow the below instructions:</blockquote><blockquote>1. Extract the name from the output.</blockquote><blockquote>2. Say “Hello, {name}.”</blockquote><p>We put the necessity of using the action by referring to the its output.</p><h4><strong>Execution</strong></h4><p>Now that all the necessary implementations are done, it’s time to execute them. Due to some peculiarities in the Agent Builder’s environment, MessagingEndUserId may not be referenced correctly. Therefore let’s use a Python script to execute this via API.</p><p>Slightly modify the script for the user verification test:</p><pre>def create_conversation(access_token, conversation_id):<br>    return requests.post(<br>        f&#39;{SF_MIAW_URL}/iamessage/api/v2/conversation&#39;,<br>        headers={<br>            &#39;Content-Type&#39;: &#39;application/json&#39;,<br>            &#39;Authorization&#39;: f&#39;Bearer {access_token}&#39;,<br>        },<br>        json={<br>            &#39;conversationId&#39;: conversation_id,<br>            &#39;esDeveloperName&#39;: SF_MIAW_DEV_NAME,<br>        }<br>    )<br><br><br>def send_message(access_token, conversation_id, message):<br>    return requests.post(<br>        f&#39;{SF_MIAW_URL}/iamessage/api/v2/conversation/{conversation_id}/message&#39;,<br>        headers={<br>            &#39;Content-Type&#39;: &#39;application/json&#39;,<br>            &#39;Authorization&#39;: f&#39;Bearer {access_token}&#39;,<br>        },<br>        json={<br>            &#39;message&#39;: {<br>                &#39;id&#39;: str(uuid.uuid4()),<br>                &#39;messageType&#39;: &#39;StaticContentMessage&#39;,<br>                &#39;staticContent&#39;: {<br>                    &#39;formatType&#39;: &#39;Text&#39;,<br>                    &#39;text&#39;: message,<br>                },<br>            },<br>            &#39;esDeveloperName&#39;: SF_MIAW_DEV_NAME,<br>            &#39;isNewMessagingSession&#39;: False,<br>        }<br>    )<br><br><br># Create a simple HTTP server to handle the callback<br>class AuthenticationCodeHandler(BaseHTTPRequestHandler):<br>    def do_GET(self):<br>        self.send_response(200)<br>        self.end_headers()<br><br>        parsed = urlparse.urlparse(self.path)<br>        params = urlparse.parse_qs(parsed.query)<br><br>        code = params.get(&#39;code&#39;, [None])[0]<br>        if code:<br>            jwt = retrieve_jwt(code)<br>            token = retrieve_authed_user_miaw_token(jwt)<br><br>            conversation_id = str(uuid.uuid4())<br>            res = create_conversation(token, conversation_id)<br><br>            # Wait a few seconds for the conversation to finish creating<br>            time.sleep(10)<br><br>            res = send_message(token, conversation_id, &#39;Hello.&#39;)<br><br>            self.wfile.write(f&#39;Authentication successful. Token: {token}&#39;.encode())<br><br>        else:<br>            self.wfile.write(b&#39;Failed to retrieve JWT.&#39;)</pre><p>After user verification, the script sends a greeting message to the Service Agent, triggering the instructions specified in Topics.</p><p>As this script doesn’t include code to handle responses from the Service Agent, results will be confirmed using the Agent Builder’s event logs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nRA5gJbUp4hCdGOIt3LwxA.png" /></figure><p>The event log at the time of action execution was as follows:</p><pre>{<br>    &quot;actionName&quot;: &quot;CustomUXTest&quot;,<br>    &quot;actionId&quot;: &quot;XXXXXXXXXXXXXXXXXX&quot;,<br>    &quot;plannerId&quot;: &quot;&quot;,<br>    &quot;isSuccess&quot;: true,<br>    &quot;duration&quot;: 159,<br>    &quot;rawInput&quot;: &quot;{\&quot;recordId\&quot;:\&quot;XXXXXXXXXXXXXXXXXX\&quot;}&quot;,<br>    &quot;rawOutput&quot;: &quot;{output=name: Guest\nid: v2/iamessage/AUTH/Salesforce/uid:uid:XXXXXXXXXXXXXXXXXX}&quot;,<br>    &quot;outputErrors&quot;: []<br>}</pre><p>The ID in the rawInput has been masked, but it was confirmed that the MessagingEndUserId value was specified, and that the authenticated user’s ID was present in the id field of rawOutput. Great!</p><h3><strong>Conclusion</strong></h3><p>In this article, we summarized the method for providing custom UX to users with the Service Agent.</p><p>Injecting context is essential to effectively leverage LLMs, and tailoring context per user is particularly important. Although not discussed in this article, Omni-channel also offers various ways to obtain unique contexts for each customer, such as injecting context from Pre-Chat.</p><p>However, Omni-channel’s UI quirks and fragmented documentation around Service Agent made for a challenging experience. Salesforce clearly focuses on selling Agentforce, but we hope they’ll equally prioritize improving the development experience.</p><p>We hope this article helps alleviate some frustrations of engineers involved in developing with Agentforce.</p><p>Thank you for reading to the end.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d0be8db760f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Accessing Agentforce Service Agent from External Web Pages]]></title>
            <link>https://medium.com/@daiki.yamashita_67366/accessing-agentforce-service-agent-from-external-web-pages-1976a8904b97?source=rss-c1b6d182e72b------2</link>
            <guid isPermaLink="false">https://medium.com/p/1976a8904b97</guid>
            <category><![CDATA[salesforce]]></category>
            <category><![CDATA[agentforce]]></category>
            <dc:creator><![CDATA[Daiki Yamashita (FLECT)]]></dc:creator>
            <pubDate>Wed, 13 Nov 2024 08:34:04 GMT</pubDate>
            <atom:updated>2024-11-14T01:04:01.274Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>This is English translation of the following original blog in Japanese:</strong></p><p><a href="https://cloud.flect.co.jp/entry/2024/11/12/203306">https://cloud.flect.co.jp/entry/2024/11/12/203306</a></p><p>Agentforce was spectacularly announced at Dreamforce 2024, and among the highlights was the introduction of Service Agent. This service allows LLM to handle customers as agent, offering more natural and flexible responses than traditional services like chatbots.</p><p>Service Agent is designed to be accessible from external web pages outside of Salesforce and can be embedded in any screen in chat format. Given the prospect of embedding a fully managed LLM directly linked to Salesforce into a web page, not trying this out is not an option.</p><p>However, there is a drawback in that it is difficult to find the right way to embed Service Agent in a web page. This is due to the fact that Service Agent is published using the mechanism of Omni-Channel, which integrates various sales channels. Omni-Channel is complex because of its vast context, and the official documentation is scattered, making it very difficult to get the necessary and sufficient information.</p><p>It’s quite unfortunate to have such a promising service yet face this situation. Therefore, in this article, we will explain the minimal necessary settings for embedding Service Agent into a web page.</p><h3><strong>Overview</strong></h3><p>In conclusion, the path to reach Service Agent from a web page is as follows:</p><pre>Browser (Web)<br>-&gt; Embedded Service Deployments<br>-&gt; Messaging Channel (Messaging Settings)<br>-&gt; Omni-Channel Flow<br>-&gt; Service Agent</pre><p>The challenging group of concepts between Browser and Service Agent are elements of Omni-Channel.</p><p>In summary, Messaging Channel represents the sales channels, which are made accessible externally through Embedded Service Deployments, and Omni-Channel Flow defines how to handle incoming inquiries to these sales channels.</p><p>It looks somewhat straightforward. But it’s only as a hindsight, after a lot of elaboration with official documents.</p><p>So let’s implement this. We will start from the elements closest to Service Agent.</p><h3><strong>Creating a Service Agent</strong></h3><p>Without a Service Agent, nothing begins. Let’s start by creating a Service Agent.</p><p>To create a Service Agent, a dedicated license is required. It’s recommended to use the playground available in the following Trailhead for trial purposes. The environment we use is also from this playground.</p><p><a href="https://trailhead.salesforce.com/content/learn/projects/quick-start-build-your-first-agent-with-agentforce/configure-an-agentforce-service-agent">Configure Agentforce for Exceptional Service</a></p><p>Service Agent can be created from the Agents section in Setup. Press the + New Agent button in the top right corner and follow the on-screen instructions to complete the process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aCO9RrTCAixWf3WSHpwjTw.png" /></figure><p>There is no difficulty in creating it, so the detailed settings are omitted. Don’t forget to Activate it after creation.</p><h3><strong>Enabling Omni-Channel</strong></h3><p>Next, we need to configure the Omni-Channel settings to expose the Service Agent externally. But first, Omni-Channel needs to be enabled.</p><p>Omni-Channel can be enabled in the Omni-Channel Settings in Setup. Although it is already enabled in the playground, check it just in case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4SJA-RIpZotAlSPLkx83Cw.png" /></figure><p>It’s properly enabled.</p><p>The Enable Skills-Based and Dicrect-to-Agent Routing option is checked, but it is not necessary for using the Service Agent and can be unchecked. Essentially, checking Enable Omni-Channel is sufficient.</p><h3><strong>Creating a Queue</strong></h3><p>Omni-Channel is designed to prevent loss of opportunities by storing content in a Fallback Queue when appropriate routing of an inquiry fails due to some reason. Therefore, we have to prepare the Queue in advance.</p><p>Queues used in Omni-Channel require a Routing Configuration, so create this first from Routing Configurations in Setup with the following settings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*Kp-t380ko-9Vi83S9gcpqQ.png" /></figure><p>Although these define routing and priority for inquiries of Omni-Channel, this details are not significant, so the explanation is omitted. For more details on each setting, refer to the official documentation <a href="https://help.salesforce.com/s/articleView?id=service.service_presence_routing_configuration_settings.htm&amp;type=5">here</a>.</p><p>Using the created TestRouting, create a Queue from the Queues section in Setup.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*udC6wNcTc01yb6ag0C1ilg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*8Y3S8d4u7KeAYDM_fTKQ8Q.png" /></figure><p>Only Routing Configuration and Supported Objects need to be set. Other items (including Queue Members not shown in the image) are unnecessary.</p><p>Here, we set Messaging Sessions as Supported Objects. These manage Omni-Channel inquiries and will be passed as inputs to the Omni-Channel Flow we will create in the next section.</p><h3><strong>Creating an Omni-Channel Flow</strong></h3><p>The Omni-Channel Flow defines how to handle inquiries received by the sales channels. Here we create a Flow to route these inquiries to the Service Agent.</p><p>You can create an Omni-Channel flow by the same way you create any other Flow. Create an Omni-Channel Flow in Flow of Setup.</p><p>Omni-Channel Flow implicitly receives the Messaging Session ID as an input, for which a variable named recordId needs to be defined in the Flow. Refer to the image below for the variable definition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WTWdnyKt7Ql2CwAsdYM1Jg.png" /></figure><p>The flow to be created here is quite simple, as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*cUa4D0gb89vChuMdV7tKkg.png" /></figure><p>Simply add the Route Work action for routing inquiries to the Service Agent. Configure Route Work as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*4DWjYmcDbTlWK3WEsSW-UQ.png" /></figure><p>Don’t forget to Activate it after creation.</p><h3><strong>Creating a Messaging Channel (Messaging Settings)</strong></h3><p>Let’s create the sales channel linked to the Omni-Channel Flow from Messaging Settings in Setup. Please note you can keep the toggle switch located in Message Settings section disabled.</p><blockquote>Note: Once a Messaging Channel is created, it cannot be deleted. It can be deactivated but will still remain in the list.</blockquote><p>When asked about the type of Messaging Channel during creation, select Messaging for In-App and Web. It uses <a href="https://developer.salesforce.com/docs/service/messaging-api/overview">Messaging API</a> to access the channel, as it means, used to access the channel from mobile apps or web.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G0WNlHpkPbeV0YGJL2aHIA.png" /></figure><p>After creation, set only the Omni-Channel Routing items. Specifically, set Routing Type to Omni-Flow, and assign the created Flow and Queue to Flow Definition and Fallback Queue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MDsPYO5q-TMbgi-HQIidnQ.png" /></figure><p>Other settings can remain default.</p><p>Don’t forget to Activate it after creation.</p><h3><strong>Creating an Embedded Service Deployment</strong></h3><p>Finally, create the Deployment to expose the Messaging Channel. This can be done from Embedded Service Deployments in Setup.</p><p>When asked about the connection method with the client during creation, select Custom Client for Messaging for In-App and Web. Finally, specify the created Messaging Channel and save.</p><p>The Deployment needs to be Published after creation, which takes about 10 minutes.</p><h3><strong>Testing with a Sample Client</strong></h3><p>Now that we’ve finished configuring Salesforce, let’s test it out in a web client.</p><p>As noted previously, Messaging In-App and Web accesses Omni-Channel via Messaging API. Thus, a client implementation is necessary, but Salesforce’s official <a href="https://github.com/Salesforce-Async-Messaging/messaging-web-api-sample-app">sample app</a> can be used for this purpose.</p><p>Though this sample app can be run on the web, we ran it locally for future analysis convenience. When running locally, pay attention to the following two points:</p><ol><li>Remove package-lock.json to avoid npm install failure due to Salesforce proxy information remaining in package-lock.json.</li><li>Remove React.StrictMode from src/index.js when running locally to prevent chat malfunction.<a href="#66f5">¹</a></li></ol><p>Once run, you can chat with the Service Agent as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q1Jj5exFyrX33Pd9R7U-Yg.png" /></figure><p>The input required to the sample app can be obtained from Code Snippet in Embedded Service Deployments.</p><p>It seems to be responding, but let’s verify if the response indeed comes from the created Service Agent. Check the logs in Agent Builder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rsMyQYJGuRpcGFdQfTBPmw.png" /></figure><p>The input content from the chat is logged. Good!</p><p>Note, the above logs are from enabling the Enrich event logs with conversational data setting, which makes logs easier to read. This can be changed from Settings in Agent Builder.</p><h3><strong>Conclusion</strong></h3><p>Thus, we successfully called the Service Agent from a web page external to Salesforce.</p><p>Agentforce is currently the product Salesforce is most actively promoting, so it’s expected that use cases for Agentforce will significantly increase this year. In this guide, in anticipation of this move, I’ve covered how to use Service Agent in external apps or web pages.</p><p>In conclusion, calling Service Agent via the Omni-Channel Messaging for In-App and Web seems the proper way. However, due to Agentforce being quite new, the appropriate way to call Service Agent via API is not sufficiently covered in official documentation, and developers must discover them by themselves. A̶r̶e̶ ̶t̶h̶e̶y̶ ̶e̶v̶e̶n̶ ̶t̶r̶y̶i̶n̶g̶ ̶t̶o̶ ̶s̶e̶l̶l̶ ̶t̶h̶i̶s̶?̶</p><p>Hopefully, developer information will be organized and clarified throughout this year.</p><p>Thank you for reading to the end.</p><p><a href="#6df9">[1]</a>: React’s feature of executing each component twice during tests to verify proper state management conflicts with chat state management, causing chat to end immediately after starting.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1976a8904b97" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Changes in Copilot Specifications Accompanying the Rebranding to Agentforce]]></title>
            <link>https://medium.com/@daiki.yamashita_67366/changes-in-copilot-specifications-accompanying-the-rebranding-to-agentforce-4a461ef3d492?source=rss-c1b6d182e72b------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a461ef3d492</guid>
            <category><![CDATA[agentforce]]></category>
            <category><![CDATA[einstein-copilot]]></category>
            <category><![CDATA[salesforce]]></category>
            <category><![CDATA[einstein]]></category>
            <dc:creator><![CDATA[Daiki Yamashita (FLECT)]]></dc:creator>
            <pubDate>Tue, 08 Oct 2024 06:06:12 GMT</pubDate>
            <atom:updated>2024-10-08T06:06:12.761Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>This is English translation of the following original blog in Japanese:</strong></p><p><a href="https://cloud.flect.co.jp/entry/2024/10/04/085909">https://cloud.flect.co.jp/entry/2024/10/04/085909</a></p><p>Agentforce was featured at Dreamforce 2024. As part of this, a hierarchical change was made by classifying Einstein Copilot as a type of Agent, and several specifications were modified from the end of August to the beginning of September.</p><p>Among these specification changes, the introduction of Agent Topics significantly impacts the development process of Einstein Copilot. In short, this change puts one additional layer between Einstein Copilot and Actions, which affects the design of the depending product.</p><p>Due to this Agent Topics, the contents of the Einstein Copilot articles we previously wrote on this blog have become outdated, which is not desirable. Therefore, in this post, we would like to write about Agent Topics.</p><h3><strong>Overview</strong></h3><p>Originally, the old specification allowed multiple Actions to be registered to the Copilot, which would autonomously invoke the necessary Action based on the user’s question. It looked something like this:</p><pre>- Copilot<br>  - Action A<br>  - Action B<br>  - Action C</pre><p>After rebranding to Agentforce, the “Topic” layer is added as a higher level, resulting in the following structure:</p><pre>- Copilot<br>  - Topic A<br>    - Action A-1<br>    - Action A-2<br>  - Topic B<br>    - Action B-1<br>    - Action B-2</pre><p>Topic is a concept akin to the “current subject”; the Copilot identifies the Topic from the user’s question first and then calls the relevant Actions assigned to that Topic as needed. It’s a kind of feature that groups multiple Actions together.</p><p>Previously, with Actions directly assigned to the Copilot, it was difficult to control the increasing number of Actions to avoid misuse. However, this problem is somewhat mitigated by Topics.</p><h3><strong>How to Assign Actions</strong></h3><p>Agent Topics has changed the flow for assigning Actions, so I’ll introduce how to do that. The method to create Actions is the same as before, so we suppose that Actions already exist.</p><p>Creating Topics and assigning Actions to Topics are both done through Agent Builder. Agent Builder is the new name for Copilot Builder. You can access Agent Builder from Agents menu on Setup.</p><p>This time, we will create a Topic for Actions that assess risks by the Copilot we introduced in <a href="https://medium.com/@daiki.yamashita_67366/using-einstein-copilot-to-avoid-missing-issues-that-require-intervention-4bbe2acb811f">previous article</a>. You can create a Topic from the menu shown in the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*5Y1PZFZ0BVPd1j8gg4MyJQ.png" /></figure><p>When you click New Topic, the following window will appear.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MNYL47TUtft44evdI5HNPA.png" /></figure><p>You need to input the following information:</p><ul><li>Topic Label</li></ul><p>Enter the name of the Topic. This name is important as it will be used by LLM when identifying relevant Topics based on user’s question.</p><ul><li>Classification Description</li></ul><p>This is the overview description of the Topic. It is used for identifying the Topic, similar to the Topic label.</p><ul><li>Scope</li></ul><p>This is a description that outlines the attitude or behavior the LLM should adopt when the Topic is selected. You can use the phrase “Your job is to XX” commonly used in prompts here. Since it is referenced only after the Topic is selected, it does not influence the selection of the Topic itself.</p><ul><li>Instructions</li></ul><p>Describe how to use the Actions related to the Topic. For instance, you might specify “use Action A if a user asks about X and Action B if a user asks about Y.”</p><p>For reference, the input we created this time is as follows:</p><blockquote>Topic label:<br>OpportunityRiskAssessment</blockquote><blockquote>Classification Description:<br>This topic treats risk assessment for an Opportunity and questions about emails that relate to an Opportunity. Set this topic if a user asks something about risk assessment.</blockquote><blockquote>Scope:<br>Your job is to assess risks or answer questions about emails that form the basis of the assessment.</blockquote><blockquote>Instructions:<br>If a user requests a risk assessment, please use RiskAssessment action. And if a user asks about emails, please use EmailMessagesQA action.</blockquote><p>Although we entered this rather casually, it works quite well.</p><p>After entering the above input and click Next, the window will transition to a screen where you can select the Actions to assign to the Topic. Select the necessary Actions and click Finish to complete the process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*egd8yKON61Q7wEdUWjdS0A.png" /></figure><p>While the sudden change to Agent Topics was initially confusing, it isn’t too difficult once you get used to it.</p><h3><strong>Ripple Effects of Agent Topics</strong></h3><p>While Agent Topics itself is not particularly difficult, there are some subtle issues probably caused by this change. As we observed behavioral changes of Copilot after rebranding, hidden internal prompts given to Copilot may have been changed.</p><p>Given that a new Topic layer has been added, changing the prompt itself is unavoidable. However, it’s concerning that the effects also appear in areas apparently unrelated to Agent Topics.</p><p>Here, We will introduce two changes we noticed.</p><h4><strong>Change in Method of Passing Objects to Actions</strong></h4><p>It’s possible to pass objects such as Account as input parameters to Actions. However, the method of passing these objects seems to have been changed.</p><p>Previously, LLM would specify the ID of the object, and the object retrieved internally by that ID is passed to the Action. After rebranding to Agentforce, it seems the values of each field of the object are passed en bloc as a JSON.</p><p>Specifically, LLM specifies JSON to the Action as follows:</p><pre>{<br>  &quot;id&quot; : &quot;0064z00002F7O1cAAF&quot;,<br>  &quot;sObjectInfo&quot; : {<br>    &quot;apiName&quot; : &quot;Opportunity&quot;,<br>    &quot;label&quot; : &quot;Opportunity&quot;<br>  },<br>  &quot;data&quot; : {<br>    &quot;Id&quot; : &quot;0064z00002F7O1cAAF&quot;,<br>    &quot;Name&quot; : &quot;Seikin Enterprise Core System Development&quot;,<br>    &quot;CreatedDate&quot; : &quot;2024-09-30T05:15:04.000Z&quot;,<br>    &quot;StageName&quot; : &quot;Closed Won&quot;,<br>    &quot;CloseDate&quot; : &quot;2024-09-29T00:00:00.000Z&quot;<br>  }<br>}</pre><p>The content of data is the fields of the input object.</p><p>While this is merely a specification change, the problem is that the contents of data specified by LLM are unstable. Which fields of the object are specified depends on LLM’s mood, so there can be cases where necessary fields for Action execution are not specified. In worse cases, data key itself may not be specified as follows.</p><pre>{<br>  &quot;id&quot; : &quot;0064z00002F7O1cAAF&quot;,<br>  &quot;sObjectInfo&quot; : {<br>    &quot;apiName&quot; : &quot;Opportunity&quot;,<br>    &quot;label&quot; : &quot;Opportunity&quot;<br>  }<br>}</pre><p>In such cases, Action execution naturally results in an error. Similarly, errors occur if required fields of the object are not specified.</p><p>To prevent this, we can specify necessary fields in the Action Instruction. Below is the prompt we wrote for receiving an Opportunity parameter:</p><blockquote>An Opportunity subject to risk assessment. The Opportunity must contain at least Opportunity ID, Opportunity Name, Stage, and Close Date in the data.</blockquote><p>However, ideally, fundamental functions like passing objects from Copilot to Actions should be ensured by the platform, so we would prefer not having to care about this. ̶A̶n̶d̶ ̶i̶s̶n̶’̶t̶ ̶t̶h̶i̶s̶ ̶c̶h̶a̶n̶g̶e̶ ̶u̶n̶r̶e̶l̶a̶t̶e̶d̶ ̶t̶o̶ ̶A̶g̶e̶n̶t̶ ̶T̶o̶p̶i̶c̶s̶?̶</p><h4><strong>Behavior for Languages Other Than English</strong></h4><p>Although there is no solid evidence, we have the impression that the tolerance towards non-English languages has decreased.</p><p>Specifically, when directing the Copilot to “provide answers in Japanese,” the frequency of being bluntly refused “Unable to answer.” seems to have increased. Occasionally, it even states “I can only respond in English,” indicating that prompts impose some limitations.</p><p>Copilot didn’t originally claim to support languages other than English, so this might mean stricter enforcement. Support for languages like Japanese is apparently planned, so let’s await official support.</p><h3><strong>Conclusion</strong></h3><p>To summarize the content this time:</p><ul><li>Agent Topics have been added, enabling the grouping of Actions.</li><li>The addition of Agent Topics has altered the implicit prompts given to Copilot.</li><li>The method of passing objectes from Copilot to Actions has i̶n̶e̶x̶p̶l̶i̶c̶a̶b̶l̶y̶ been changed.</li><li>The tolerance towards languages other than English has decreased (or so it seems).</li></ul><p>Experiencing firsthand how platform changes can significantly impact existing LLM products has been quite educational. When using an LLM platform, the stability of the platform itself must be considered, requiring careful product selection.</p><p>Building on one’s own using tools like LangChain has this advantage but increases development workload, which is a dilemma. We will keep an eye on market trends to see which methods will become standard in the future.</p><p>That’s all. Thank you for reading to the end.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a461ef3d492" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Einstein Copilot to Avoid Missing Issues that Require Intervention]]></title>
            <link>https://medium.com/@daiki.yamashita_67366/using-einstein-copilot-to-avoid-missing-issues-that-require-intervention-4bbe2acb811f?source=rss-c1b6d182e72b------2</link>
            <guid isPermaLink="false">https://medium.com/p/4bbe2acb811f</guid>
            <category><![CDATA[einstein-copilot]]></category>
            <category><![CDATA[einstein]]></category>
            <category><![CDATA[salesforce]]></category>
            <dc:creator><![CDATA[Daiki Yamashita (FLECT)]]></dc:creator>
            <pubDate>Thu, 12 Sep 2024 00:38:59 GMT</pubDate>
            <atom:updated>2024-10-08T05:44:52.106Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>This is English translation of the following original blog in Japanese:</strong></p><p><a href="https://cloud.flect.co.jp/entry/2024/08/28/165341">https://cloud.flect.co.jp/entry/2024/08/28/165341</a></p><p>In this article, we present a use case for Einstein Copilot to assess the risks of Opportunities.</p><p>Tracking the status of deals is one of the major challenges for CRM platforms, including Salesforce. People responsible for managing deals, especially those managing multiple deals, have a strong need for quick status checks and accurate means to judge whether intervention is necessary.</p><p>In fact, this need fits perfectly with Einstein Copilot. Summarizing abstract situations is one of the tasks that LLMs excel at, and since it is a Salesforce service, accessing the various records that serve as the source data for summarization is straightforward.</p><p>Using Einstein Copilot, you can check the status of an Opportunity in the following way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9BLdEB37bEPCVX8Yan1lqA.png" /></figure><p>(Since this article is a translation of a Japanese article, please excuse the presence of Japanese text in the images. And also the company names and so forth shown in the image are generated by the LLM and are fictitious.)</p><p>In this image, we ask Einstein Copilot to “assess the risk of Seikin Enterprise’s Opportunity,” and Einstein Copilot responds with a risk score, an overview of the Opportunity’s status, and details of the risks.</p><p>The key point is that you can easily extract only the necessary information without tracking the details of the Opportunity. This showcases the strength of the LLM in summarizing based on specified viewpoints.</p><p>It’s cool, isn’t it? So let’s dive right into how to implement this.</p><h3><strong>Implementation Overview</strong></h3><p>The use case introduced at the above can be realized by implementing a Copilot Action that performs risk assessment. In this case, we can use a Flex Prompt Template as the Copilot Action. The Flex Prompt Template is a template for prompts used to generate responses from a LLM based on various data. Details will be described later.</p><p>To perform risk assessment, some base data is necessary. This time, we will link customer interaction emails to the Opportunity and retrieve them during the risk assessment.</p><p>The content of the emails will be stored in the Standard Salesforce Object EmailMessage, but Salesforce does not have a built-in function to retrieve EmailMessage from a Flex Prompt Template. Fortunately, Apex can be executed from Flex Prompt Template, so we will retrieve the EmailMessage via Apex.</p><p>The flow from Einstein Copilot to EmailMessages is as follows:</p><pre>Einstein Copilot<br>→ Copilot Action<br>→ Flex Prompt Template<br>→ Apex<br>→ EmailMessage</pre><p>The workflow for implementation is as follows:</p><ol><li>Create EmailMessage linked to an Opportunity</li><li>Create Flex Prompt Template</li><li>Implement Apex to retrieve EmailMessage</li><li>Create Copilot Action</li></ol><p>Let’s proceed step by step.</p><h3><strong>Creating EmailMessages Linked to an Opportunity</strong></h3><p>As a preliminary task before implementation, we need to create an Opportunity to which the EmailMessage will be linked and the text of the emails to be registered. The former is straightforward, and the latter can be generated appropriately by the LLM, so there is nothing special to explain.</p><p>There are several ways to create an EmailMessage linked to an Opportunity:</p><ul><li>Actually sending an email from the Opportunity’s record page</li><li>Using <a href="https://help.salesforce.com/s/articleView?id=sf.email_my_email_2_sfdc.htm&amp;type=5">Email to Salesforce</a></li><li>Using <a href="https://developer.salesforce.com/tools/data-loader">Salesforce Data Loader</a></li><li>Using Apex</li></ul><p>This time, we registered emails via Apex. Just write the Apex below and execute it from Flow etc.</p><pre>public class DummyEmailRegistration {<br><br>    private static String T = &#39;tanaka@company.test&#39;;<br>    private static String S = &#39;sato@customer.test&#39;;<br><br>    private static List&lt;E&gt; es = new List&lt;E&gt;<br>        { new E(Datetime.now().addHours(-20), T, S, &#39;(email-subject-1)&#39;, &#39;(emial-body-1)&#39;)<br>        , new E(Datetime.now().addHours(-19), S, T, &#39;(email-subject-2)&#39;, &#39;(emial-body-2)&#39;)<br>        , new E(Datetime.now().addHours(-18), T, S, &#39;(email-subject-3)&#39;, &#39;(emial-body-3)&#39;)<br>        // ... omit ...<br>        };<br><br>    @InvocableMethod<br>    public static List&lt;String&gt; insertEmails() {<br>        List&lt;EmailMessage&gt; emails = new List&lt;EmailMessage&gt;();<br>        for (E e : es) {<br>            EmailMessage email = new EmailMessage();<br>            email.MessageDate = e.dt;<br>            email.FromAddress = e.fromAddr;<br>            email.ToAddress = e.toAddr;<br>            email.Subject = e.subject;<br>            email.TextBody = e.textBody;<br>            email.RelatedToId = &#39;(your-opportunity-id)&#39;;<br>            // 3 indicates &#39;Sent&#39;<br>            email.Status = &#39;3&#39;;<br>            // set to true if the email is incoming<br>            email.Incoming = e.toAddr == T;<br>            emails.add(email);<br>        }<br>        insert emails;<br>        return new List&lt;String&gt;();<br>    }<br><br>    private class E {<br>        Datetime dt;<br>        String fromAddr;<br>        String toAddr;<br>        String subject;<br>        String textBody;<br><br>        public E(<br>            Datetime dt,<br>            String fromAddr,<br>            String toAddr,<br>            String subject,<br>            String textBody<br>        ) {<br>            this.dt = dt;<br>            this.fromAddr = fromAddr;<br>            this.toAddr = toAddr;<br>            this.subject = subject;<br>            this.textBody = textBody;<br>        }<br>    }<br>}</pre><h3><strong>Creating a Flex Prompt Template</strong></h3><p>For those who are unfamiliar with Flex Prompt Template, we would explain briefly about it first.</p><p>Einstein Copilot has a functionality named “Prompt Template” which will serve as a template of your prompt for the LLM. There are various types of Prompt Templates depending on the purpose, such as Field Generation, Record Summary, and so on.</p><p>Flex is one of these types and is used when you want Einstein Copilot to generate answers from a specific viewpoint. It is similar to Record Summary in the sense of generating answers in chat, but Flex can be considered as a more versatile version.</p><p>Let’s take a look in practice. To create a new Prompt Template, press the New Prompt Template button in the Prompt Builder within the Setup. Note that if Einstein Copilot is not enabled for your organization, Prompt Builder will not be displayed.</p><p>Press New Prompt Template to open a popup window where you need to input required information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7FqB9Bxi2CQcQimFtBOEwA.png" /></figure><p>The important part is the Define Sources section, where you specify the data that will serve as Flex Prompt Template’s input. The input parameter can be selected from Object and Free Text, and in both cases, the actual parameter will be set by the LLM at runtime. This parameter setting should follow the instruction of each parameter when defining Copilot Action.</p><p>Since we want to perform risk assessment based on emails linked to Opportunity, we will specify an Object as the Source Type and choose the Opportunity as Object.</p><p>After entering the necessary details, press Next to display the following screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TMpybk_c3u_lO1Sqcw-rKA.png" /></figure><p>Here you specify a LLM to be used and the prompt given to the LLM.</p><p>Initially, the LLM to be used is set to OpenAI GPT 3.5 Turbo, but it is a fundamental rule in MLOps to use the highest-performing LLM available, so be sure to change it to Default GPT 4 Omni configured model.</p><p>This time, we would use a fictitious system development project as Opportunity. Here’s the prompt:</p><blockquote>You are an AI assistant to a project manager for the XXXX Systems. Your task is to review the given information exchange related to the system development project, summarize its contents, and report any signs of problems that may require intervention in the project. Please omit any text outside the specified format.</blockquote><blockquote>Please scrutinize the signs of problems from the following perspectives:</blockquote><blockquote>- Does it affect the development schedule?<br>- Does it affect the quality of deliverables?<br>- Does it affect the project’s profitability?</blockquote><blockquote>Follow the format below for the report:</blockquote><blockquote>```<br>[Evaluation]<br>Indicate the presence or absence of risk as a score from 1 to 10.<br>The lower the value, the higher the risk of problems.</blockquote><blockquote>[Summary]<br>Write the summary of the information exchange related to the project here.</blockquote><blockquote>[Risk]<br>If there are signs of a problem, list them here.<br>If there are no signs of problems, write “None”.<br>```</blockquote><blockquote>Here is a sample of the report:</blockquote><blockquote>```<br>[Evaluation]<br>3</blockquote><blockquote>[Summary]<br>The requirements definition has been completed without any particular problems. However, inconsistencies were found in the specifications during the design phase, and we are currently waiting for the client’s specification review. We have inquired about the timing of specification confirmation, but the response is on hold. In addition, the client has inquired about adjusting the contract content from the month after next, but there has been no response from XXXX System.</blockquote><blockquote>[Risk]<br>1. Delay in schedule due to prolonged specification review<br>If the client’s specification review is prolonged, it may affect the development schedule.<br>2. Uncertainty about adjusting contract content from the month after next<br>There is no response to the client’s inquiry, and the outlook for adjusting contract content is unclear. In the worst case, it may not be possible to renew the contract.<br>```</blockquote><blockquote>Below is the correspondence between XXXX System and the client.</blockquote><blockquote>```<br>(Leave this blank for now)<br>```</blockquote><blockquote>Now, generate the report.</blockquote><p>The part labeled “<em>(Leave this blank for now)</em>” will later be replaced by an Apex method to retrieve EmailMessages. After implementing Apex, we will revisit this setting.</p><p>You might think it would be easier to complete Apex implementation first, but that is actually impossible. This is because the Apex called from a Flex Prompt Template must be implemented with the following specific procedures, and one of these involves referencing the existing Flex Prompt Template name.</p><p>In short, for the Apex, the Flex Prompt Template must exist first, so at the time of creating the Flex Prompt Template, APEX cannot be set. If you put a fictional Flex Prompt Template name in the Apex, a compilation error will occur. Consequently, the definition of Flex Prompt Template must come first.</p><p>With the creation of the Flex Prompt Template provisionally complete, save the current contents.</p><h3><strong>Implementing Apex to Retrieve EmailMessage</strong></h3><p>As mentioned earlier, the Apex called from a Flex Prompt Template must be implemented with the following specific procedures. See the code below:</p><pre>public class GetEmailMessages {<br>    @InvocableMethod(CapabilityType=&#39;FlexTemplate://OpportunityStatusSummaryDemo&#39;)<br>    public static List&lt;Response&gt; getEmailMessages(List&lt;Request&gt; requests) {<br>        Id id = requests[0].opportunity.Id;<br>        List&lt;EmailMessage&gt; emails = [<br>            SELECT<br>                MessageDate<br>              , FromAddress<br>              , ToAddress<br>              , Subject<br>              , TextBody<br>            FROM<br>                EmailMessage<br>            WHERE<br>                RelatedToId = :id<br>            ORDER BY<br>                MessageDate ASC<br>        ];<br><br>        List&lt;String&gt; formatted = new List&lt;String&gt;();<br>        for (EmailMessage email : emails) {<br>            formatted.add(format(email));<br>        }<br>        String result = String.join(formatted, &#39;\n---\n&#39;);<br><br>        List&lt;Response&gt; out = new List&lt;Response&gt;();<br>        out.add(new Response(result));<br><br>        return out;<br>    }<br><br>    private static String format(EmailMessage e) {<br>        String s = &#39;&#39;;<br>        s += &#39;datetime: &#39; + e.MessageDate + &#39;\n&#39;;<br>        s += &#39;from: &#39; + e.FromAddress + &#39;\n&#39;;<br>        s += &#39;to: &#39; + e.ToAddress + &#39;\n&#39;;<br>        s += &#39;subject: &#39; + e.Subject + &#39;\n&#39;;<br>        s += &#39;\n&#39;;<br>        s += e.TextBody;<br><br>        return s;<br>    }<br><br>    public class Request {<br>        @InvocableVariable<br>        public Opportunity opportunity;<br>    }<br><br>    public class Response {<br>        @InvocableVariable<br>        public String Prompt;<br><br>        public Response(String prompt) {<br>            this.Prompt = prompt;<br>        }<br>    }<br>}</pre><p>Overall, what it does is SELECT the EmailMessage and return a string converted into the following format.</p><pre>datetime: Date and Time<br>from: Sender<br>to: Recipient<br>subject: Title<br><br>Email Body<br>---<br>datetime: Date and Time<br>from: Sender<br>to: Recipient<br>subject: Re: Title<br><br>Email Body</pre><p>The specific procedures required by the Flex Prompt Template are as follows:</p><ol><li>Specifying CapabilityType in @InvocableMethod</li><li>Matching the request parameters to the input parameters of the Flex Prompt Template</li><li>Using a specific class for response parameters</li></ol><p>At the beginning of the code, @InvocableMethod is specified and a CapabilityType is set to it; this is the first procedure. The content to specify for CapabilityType is defined for each type of Prompt Template, which can be found <a href="https://help.salesforce.com/s/articleView?id=sf.prompt_builder_ground_apex.htm&amp;type=5">here</a>. For Flex, specify FlexTemplate://(your-prompt-template-name). Moving back and forth between Prompt Builder and Apex is due to this…</p><p>The second procedure requires that the request parameter is a self-defined class, and its properties must match the input parameters specified when creating the Flex Prompt Template. The input parameter must have its name and type that exactly follow the definitions in the Prompt Template, and failure to follow this procedure will result in a compilation error. This time, we have set the Opportunity object to be proposed as a variable named opportunity.</p><p>Even if a parameter is needed on the Prompt Template side but not on the Apex side, it still must be defined in the request class. Missing definitions will also result in a compilation error.</p><p>The last procedure requires defining a class with a property named Prompt for the response. Just mimic the Response class in the provided code.</p><p>With the Apex definition complete, return to Prompt Builder to set up the Apex. Select the defined Apex from Resource at the top right of the Prompt Builder screen and replace “<em>(Leave this blank for now)</em>” with it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*LuNtfCbCbHc0P5c4d6ePEA.png" /></figure><h3><strong>Creating Copilot Action</strong></h3><p>Finally, create a Copilot Action based on the Flex Prompt Template. There are no difficult points in creating it, so we will skip the details. The method for creating Copilot Action is also introduced in a <a href="https://medium.com/@daiki.yamashita_67366/using-data-cloud-vector-database-as-rag-storage-for-einstein-copilot-e31bd5582b20">previous article</a>, so refer to it if necessary. Be sure to set the created Copilot Action to Einstein Copilot as well.</p><p>When you try the embedded Copilot Action, it will look like the image shown at the beginning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9BLdEB37bEPCVX8Yan1lqA.png" /></figure><h3><strong>Considerations on Design</strong></h3><p>Lastly, I would like to discuss the problems with the introduced implementation and insights on design obtained through the implementation.</p><p>The initial use case is fulfilled by the previous chapter. But there is a shortcoming that it cannot respond to inquiries about individual emails. In other words, even if a problem of an Opportunity is identified, Einstein Copilot cannot answer for requests to provide emails containing the problem’s details.</p><p>This issue arises because the content of emails is contained within Copilot Action and not exposed to Einstein Copilot. This monolithic implementation of two actions, retrieving and evaluating the email, limits the functionality of LLM. This is a good (or bad) example of poor design.</p><p>To improve this, Copilot Action needs to be implemented in two separate parts:</p><ul><li>Action to retrieve emails for the Opportunity</li><li>Action to assess the risk of the Opportunity based on email content</li></ul><p>Implementing this way allows it to respond to additional questions such as the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FK9Rw14eO0CyA88Sljapjw.png" /></figure><p>In the image above, we ask Einstein Copilot to “Please show me an email reporting the crucial problem,” and Einstein Copilot responds with the email content. It’s cool, isn’t it?</p><p>There are variations of the methods to implement this action split:</p><ol><li>Input the result of email retrieval action as Free Text to the risk assessment action</li><li>Independently retrieve emails in the risk assessment action apart from the email retrieval action</li></ol><p>From our experience, the second approach seems better. The first approach requires the email retrieval to be executed before the risk assessment, increasing dependency on the execution plan generated by the LLM, making action results more unstable. Therefore, although it may seem redundant, providing small-grained actions that can track the larger process while ensuring that individual actions are executable independently would be the best.</p><p>Splitting action itself is able to be implemented with the knowledge introduced in this article, so please give it a try.</p><h3><strong>Conclusion</strong></h3><p>This article covered the introduction of a use case and thoughts on action design. Key points are as follows:</p><ul><li>Einstein Copilot can streamline information extraction tasks from specific viewpoints</li><li>Flex Prompt Template can be used for this tasks</li><li>Designs need to be considered to enable the tracking of the answering process of actions</li></ul><p>Information extraction tasks in daily operations can incur significant costs, so the use cases introduced here have great potential and are expected to meet increased demand in the future.</p><p>Regarding implementation, writing Apex to retrieve EmailMessage linked to an Opportunity is somewhat cumbersome, and it would be nice to have a built-in easy retrieval method. Hopefully Salesforce will address this inconvenience.</p><p>That’s all. Thank you for reading to the end.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4bbe2acb811f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Data Cloud Vector Database as RAG Storage for Einstein Copilot]]></title>
            <link>https://medium.com/@daiki.yamashita_67366/using-data-cloud-vector-database-as-rag-storage-for-einstein-copilot-e31bd5582b20?source=rss-c1b6d182e72b------2</link>
            <guid isPermaLink="false">https://medium.com/p/e31bd5582b20</guid>
            <category><![CDATA[einstein]]></category>
            <category><![CDATA[salesforce]]></category>
            <category><![CDATA[einstein-copilot]]></category>
            <category><![CDATA[salesforce-data-cloud]]></category>
            <dc:creator><![CDATA[Daiki Yamashita (FLECT)]]></dc:creator>
            <pubDate>Wed, 21 Aug 2024 08:00:42 GMT</pubDate>
            <atom:updated>2024-08-21T08:00:42.215Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>This is English translation of the following original blog in Japanese:</strong></p><p><a href="https://cloud.flect.co.jp/entry/2024/08/05/130721">https://cloud.flect.co.jp/entry/2024/08/05/130721</a></p><p>Einstein Copilot is an AI assistant service provided by Salesforce. By giving instructions through chat, it can perform tasks such as searching records and drafting email texts by natural language. Since it can handle tedious tasks, it is probably a valuable service for those who use Salesforce regularly.</p><p>The subtle issue with Einstein Copilot is that the default search function only targets CRM records, and it cannot be used to search Data Cloud data.</p><p>If Einstein Copilot is able to use external data imported into Data Cloud, you can leverage any data of yours for more flexible CRM activities. In fact, this synergy is introduced as “one of the strongest examples” in <a href="https://www.salesforce.com/news/stories/data-cloud-vector-database-availability/">Salesforce’s official article</a>, so if there is available data externally, there is almost no reason not to integrate it.</p><p>OK. Let’s integrate them, but how? This is the problem. Unfortunately, there is almost no official information on how to integrate these services, and even if there is, it generally stays at “please integrate with APEX.”</p><p>However, it would be a waste to leave something with potential, so we would like to introduce specific integration steps in this article to fill this gap.</p><h3><strong>What to Do</strong></h3><p>This time, we will add a Custom Action to Einstein Copilot to perform vector searches using the Data Cloud Vector Database.</p><p>The flow from Einstein Copilot to the Data Cloud Vector Database is as follows:</p><pre>Einstein Copilot<br>→ Custom Action<br>→ Flow<br>→ APEX Action<br>→ Data Cloud Vector Database</pre><p>Since Salesforce Flow can be used in the Custom Action of Einstein Copilot, APEX is executed via Flow to issue a query to the Data Cloud Vector Database.</p><p>Querying the Data Cloud Vector Database is somewhat complicated, requiring authentication by a Connected App to use the Query API. In other words, authentication is performed over the internet, and the API is called. It feels complicated to go through the internet just to link Salesforce services, but unfortunately, there seems to be no other integration method at present.</p><p>Additionally, using the Query API of Data Cloud requires a dedicated access token, and the access token obtained from the Connected App cannot be used directly. There are several points where Data Cloud is slightly inflexible. We will mention these precautions as needed when they become necessary.</p><p>So, let’s get started with the implementation.</p><h3><strong>Preparing the Data Cloud Vector Database</strong></h3><p>First, create a Search Index which is required to use the Data Cloud Vector Database.</p><p>There is nothing particularly difficult, just select Easy Setup from the creation screen, choose the DMO to be searched, and press Save to complete. That’s all.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XUnTyWTqi2uQT8RsFE3UnQ.png" /></figure><p>In Easy Setup, Embedding Model and fields used for search are automatically selected. If you don’t like the automatically set content, you can also set them by yourself from Advanced Setup.</p><p>Available Embedding Models are as follows:</p><ul><li><a href="https://huggingface.co/intfloat/e5-large-v2">E5 Large V2 Embedding Model</a></li><li><a href="https://huggingface.co/intfloat/multilingual-e5-large">Multilingual E5 Large Embedding Model</a></li></ul><p>Even if you choose Advanced Setup, you cannot specify the chunk size, and it is automatically determined. We hope additional tuning items will be available in the future.</p><p>When you create the Search Index, the following DMOs with API names are created:</p><ul><li>(your-dmo-name)_index_dlm</li><li>(your-dmo-name)_chunk_dlm</li></ul><p>The first one is a search index that holds the Embedding, and the second one is a chunk that holds the text corresponding to the index. By specifying these DMOs in SQL for the Query API, vector searches can be executed.</p><h3><strong>Preparing the Connected App</strong></h3><p>As mentioned at the beginning, Connected App is necessary since access to the Data Cloud Vector Database has to be done over the internet.</p><p>Check the boxes for Enable OAuth Settings and Enable Client Credentials Flow, and set the following in the OAuth Scope:</p><ul><li>Manage user data via APIs (api)</li><li>Perform ANSI SQL queries on Data Cloud (cdp_query_api)</li></ul><h3><strong>Defining the APEX Action</strong></h3><p>We will write the process to query the Data Cloud Vector Database by APEX.</p><p>The objective is to call the Query API of Data Cloud, but as shown below, this requires three API calls in total.</p><ol><li>Obtain an access token from the Connected App</li><li>Exchange the access token from step 1 for a Data Cloud access token</li><li>Use the access token from step 2 to call the Data Cloud Query API</li></ol><p>The critical point is step 2, where the access token obtained from the Connected App cannot be used directly for the Query API. To call the Query API, the access token obtained from the Connected App must be converted to a Data Cloud access token. This conversion process can be executed through the token exchange API endpoint provided by Salesforce.</p><p>Each of these processes will be implemented in the following sections.</p><h4><strong>Obtaining an Access Token from Connected App</strong></h4><p>This is a common process, so there are no particularly difficult points.</p><pre>    private static TokenResponese retrieveSalesforceToken(String endpoint, String clientId, String clientSecret) {<br>        Map&lt;String, String&gt; params = new Map&lt;String, String&gt;();<br>        params.put(&#39;grant_type&#39;, &#39;client_credentials&#39;);<br>        params.put(&#39;client_id&#39;, clientId);<br>        params.put(&#39;client_secret&#39;, clientSecret);<br>        HttpResponse res = post(endpoint, params);<br><br>        JSONParser parser = JSON.createParser(res.getBody());<br>        return (TokenResponese) parser.readValueAs(TokenResponese.class);<br>    }<br><br>    private static HttpResponse post(String url, Map&lt;String, String&gt; params) {<br>        HttpRequest req = new HttpRequest();<br>        req.setEndpoint(url);<br>        req.setMethod(&#39;POST&#39;);<br>        req.setHeader(&#39;Content-Type&#39;, &#39;application/x-www-form-urlencoded&#39;);<br>        req.setBody(toParamStr(params));<br>        return new Http().send(req);<br>    }<br><br>    private static String toParamStr(Map&lt;String, String&gt; params) {<br>        List&lt;String&gt; out = new List&lt;String&gt;();<br>        for (String key : params.keySet()) {<br>            out.add(key + &#39;=&#39; + params.get(key));<br>        }<br>        return String.join(out, &#39;&amp;&#39;);<br>    }<br><br>    private class TokenResponese {<br>        String access_token;<br>        String instance_url;<br>    }</pre><p>What we are doing is simple, but the code tends to bloat unnecessarily in APEX…</p><h4><strong>Exchanging the Access Token for a Data Cloud Access Token</strong></h4><p>Salesforce’s token exchange endpoint is implemented with OAuth 2.0 Custom Grant Type, so basically, it involves doing what we did in retrieveSalesforceToken again for a different endpoint.</p><p>Once you understand the content of the Custom Grant Type, there are no particularly difficult points here either.</p><pre>    private static TokenResponese exchageSalesforceTokenForDataCloudToken(String endpoint, String sfToken) {<br>        Map&lt;String, String&gt; params = new Map&lt;String, String&gt;();<br>        params.put(&#39;grant_type&#39;, &#39;urn:salesforce:grant-type:external:cdp&#39;);<br>        params.put(&#39;subject_token&#39;, sfToken);<br>        params.put(&#39;subject_token_type&#39;, &#39;urn:ietf:params:oauth:token-type:access_token&#39;);<br>        HttpResponse res = post(endpoint, params);<br><br>        JSONParser parser = JSON.createParser(res.getBody());<br>        return (TokenResponese) parser.readValueAs(TokenResponese.class);<br>    }d</pre><p>Both are compliant with OAuth’s Token endpoint, so most of the code can be reused. I̶t̶ ̶w̶o̶u̶l̶d̶ ̶b̶e̶ ̶n̶i̶c̶e̶ ̶i̶f̶ ̶t̶o̶k̶e̶n̶ ̶e̶x̶c̶h̶a̶n̶g̶e̶ ̶i̶t̶s̶e̶l̶f̶ ̶w̶a̶s̶n̶’̶t̶ ̶n̶e̶c̶e̶s̶s̶a̶r̶y̶.̶</p><h4><strong>Calling Data Cloud Query API</strong></h4><p>First, implement the template for calling the Query API.</p><pre>    private static HttpResponse query(String endpoint, String token, String sql) {<br>        Map&lt;String, String&gt; headers = new Map&lt;String, String&gt;();<br>        headers.put(&#39;Authorization&#39;, &#39;Bearer &#39; + token);<br><br>        String json = &#39;{&quot;sql&quot;: &quot;&#39; + sql + &#39;&quot;}&#39;;<br><br>        return postJson(endpoint, json, headers);<br>    }<br><br>    private static HttpResponse postJson(String url, String json, Map&lt;String, String&gt; headers) {<br>        HttpRequest req = new HttpRequest();<br>        req.setEndpoint(url);<br>        req.setMethod(&#39;POST&#39;);<br>        req.setHeader(&#39;Content-Type&#39;, &#39;application/json&#39;);<br>        req.setBody(json);<br><br>        for (String key : headers.keySet()) {<br>            req.setHeader(key, headers.get(key));<br>        }<br><br>        return new Http().send(req);<br>    }</pre><p>Since we are just specifying the Authorization header and posting JSON, there are no particularly difficult points at this stage.</p><p>A confusing point of the Query API is the way to write the SQL passed as the arguments. To perform a vector search, you need to use a dedicated function called vector_search. This is used in the following notation.</p><pre>SELECT * FROM<br>  vector_search(<br>    TABLE(&lt;your-index-dmo&gt;),<br>    &#39;&lt;search-keyword&gt;&#39;,<br>    &#39;&lt;pre-filtering-condition&gt;&#39;,<br>    &lt;top-k&gt;<br>  )</pre><p>top-k is an argument to specify how many top results to retrieve, and you specify an integer value. pre-filtering-condition is an argument to describe the condition to narrow down the records before the vector search. This time, we will not use pre-filtering-condition.</p><p>A sample filled the placeholders with actual arguments is as follows.</p><pre>SELECT * FROM<br>  vector_search(TABLE(your_index__dlm), &#39;test&#39;, &#39;&#39;, 1)</pre><p>It means performing a vector search with the keyword test using the Search Index DMO your_index__dlm and retrieving the top 1 result by score. Since an empty string is specified for the filtering condition, no records are narrowed down.</p><p>Although vector search itself is possible with just this, the result becomes somewhat plain as the index only contains Embedding information. Therefore, it is better to join and retrieve the chunk holding a part of the original text as follows.</p><pre>SELECT<br>  index.score__c<br>, chunk.Chunk__c<br>FROM<br>  vector_search(TABLE(your_index__dlm), &#39;test&#39;, &#39;&#39;, 1) index<br>JOIN<br>  your_chunk__dlm chunk<br>    ON index.RecordId__c = chunk.RecordId__c</pre><p>So, with the SQL arguments clarified, let’s finish up by connecting the functions defined so far.</p><pre>public class EdgeTechTest {<br><br>    private static String SF_TOKEN_ENDPOINT = &#39;https://(your-org).my.salesforce.com/services/oauth2/token&#39;;<br>    private static String SF_TOKEN_EXCHANGE_ENDPOINT = &#39;https://(your-org).my.salesforce.com/services/a360/token&#39;;<br>    private static String SF_CLIENT_ID = &#39;(your-client-id)&#39;;<br>    private static String SF_CLIENT_SECRET = &#39;(your-client-secret)&#39;;<br><br>    @InvocableMethod<br>    public static List&lt;String&gt; getAccountNames(List&lt;String&gt; keywords) {<br>        TokenResponese sfToken = retrieveSalesforceToken(SF_TOKEN_ENDPOINT, SF_CLIENT_ID, SF_CLIENT_SECRET);<br>        TokenResponese dcToken = exchageSalesforceTokenForDataCloudToken(SF_TOKEN_EXCHANGE_ENDPOINT, sfToken.access_token);<br><br>        String keyword = keywords[0];<br>        String queryEndpoint = toQueryEndpoint(dcToken.instance_url);<br>        String sql = &#39;&#39;;<br>        sql += &#39; SELECT&#39;;<br>        sql += &#39;   index.score__c&#39;;<br>        sql += &#39; , chunk.Chunk__c&#39;;<br>        sql += &#39; FROM&#39;;<br>        sql += &#39;   vector_search(TABLE(your_index__dlm), \&#39;&#39; + keyword + &#39;\&#39;, \&#39;\&#39;, 1) index&#39;;<br>        sql += &#39; JOIN&#39;;<br>        sql += &#39;   your_chunk__dlm chunk&#39;;<br>        sql += &#39;     ON index.RecordId__c = chunk.RecordId__c&#39;;<br>        HttpResponse res = query(queryEndpoint, dcToken.access_token, sql);<br><br>        List&lt;String&gt; result = new List&lt;String&gt;();<br>        result.add(res.getBody());<br><br>        return result;<br>    }<br><br>    private static String toQueryEndpoint(String instanceUrl) {<br>        return &#39;https://&#39; + instanceUrl + &#39;/api/v2/query&#39;;<br>    }<br><br>    // ... insert the functions defined so far here ...<br>}</pre><p>Note that client ID and secret are defined as constants in a rough manner, but they should be managed appropriately. This is omitted here.</p><h3><strong>Defining a Flow</strong></h3><p>Define the Flow to be used in the Custom Action. There is nothing special and it can be defined in the same way as a normal flow.</p><p>When Einstein Copilot uses Flow, the content of the input and output is defined by the resources in Flow. By checking the Available for Input / Output checkboxes in the resource creation screen, the resources are automatically recognized as input and output targets of the Flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S1rqnAiz2Xg-ItUFl0rvRA.png" /></figure><p>This time, we will implement the Flow to receive the search keyword as input and return the result obtained from the vector search as output. There are no particularly difficult points, so the details are omitted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jweNasApY5vfZkZa3x79Lw.png" /></figure><h3><strong>Defining a Custom Action</strong></h3><p>You can define a Custom Action from Einstein Copilot Actions in Setup.</p><p>Press New Copilot Action and specify the Flow you created earlier on the screen. On the following screen, the resources specified in the Flow will be displayed as items in Input/Output as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*26PI2LsR5z0RQR9JqdK-XQ.png" /></figure><p>On this screen, you need to provide a natural language description for the entire Custom Action and the contents of each Input/Output item. Einstein Copilot will use the description provided here to automatically determine whether to call the Custom Action and the contents of the Input/Output.</p><p>Additionally, you can specify whether input parameters are required using checkboxes. The settings I configured are shown in the image above.</p><h3><strong>Setting a Custom Action in Einstein Copilot</strong></h3><p>Set the Custom Action created in Copilot Builder. You can open Copilot Builder from the Einstein Copilots section in Setup.</p><p>To configure the Custom Action, you need to deactivate Einstein Copilot first, so make sure to deactivate it. Then, simply assign the Custom Action created the above from the Copilot Action Library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*Mqx79zA7fMtF3dmMHF9E0A.png" /></figure><p>After assigning, don’t forget to activate the deactivated Einstein Copilot.</p><p>This completes all the steps.</p><h3><strong>Testing</strong></h3><p>Let’s test it.</p><p>You can use any data for the search target, but this time I borrowed a sample from <a href="https://python.langchain.com/v0.2/docs/tutorials/retrievers/#documents">LangChain</a>. This sample performs a vector search on the following five sentences:</p><ul><li>Dogs are great companions, known for their loyalty and friendliness.</li><li>Cats are independent pets that often enjoy their own space.</li><li>Goldfish are popular pets for beginners, requiring relatively simple care.</li><li>Parrots are intelligent birds capable of mimicking human speech.</li><li>Rabbits are social animals that need plenty of space to hop around.</li></ul><p>The LangChain documentation states that when searching with Cat, the second sentence from the top is returned, and when searching with Shark, the third sentence from the top is returned. Let’s try this with Einstein Copilot.</p><p>Let’s try it in the Conversation Preview of Copilot Builder. First, with Cat.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GeNW2NKTmJTiO8te5dyrwg.png" /></figure><p>It’s a bit hard to see as the JSON is displayed as is, but you can see that the second sentence from the top is returned in the right pane of the image. In the left pane of the image, you can see that Einstein Copilot has specified Cat as input. Looks good.</p><p>Next, let’s see what happens when we specify Shark.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cbSpiXQ6ls5irfCDUVj9sg.png" /></figure><p>The third sentence from the top is returned. The score is slightly lower than the previous result, possibly because the word is not directly included in the text.</p><p>This time, the response JSON is displayed as is, but it seems there is quite a bit of room for customization, such as embedding it in a Prompt Template to generate a nice response with LLM.</p><h3><strong>Conclusion</strong></h3><p>So, we were able to perform vector search by collaborating Einstein Copilot with Data Cloud.</p><p>As mentioned at the beginning, Einstein Copilot is a feature that affects the daily efficiency of people who use Salesforce regularly, so it was a shame that the data reference was limited to within the CRM. We think it is quite significant that this constraint can be eliminated through the linkage shown this time.</p><p>It is a bit inconvenient that direct linkage with the Data Cloud Vector Database is not possible and it needs to go through the internet once, but I hope this will be improved in future updates.</p><p>That’s all. Thank you for reading to the end.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e31bd5582b20" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Showing inference result of Einstein Discovery as Recommendations via Einstein Next Best Action]]></title>
            <link>https://medium.com/@daiki.yamashita_67366/showing-inference-result-of-einstein-discovery-as-recommendations-via-einstein-next-best-action-a1a7e4361f08?source=rss-c1b6d182e72b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1a7e4361f08</guid>
            <category><![CDATA[einstein-next-best-action]]></category>
            <category><![CDATA[einstein]]></category>
            <category><![CDATA[einstein-discovery]]></category>
            <category><![CDATA[salesforce]]></category>
            <dc:creator><![CDATA[Daiki Yamashita (FLECT)]]></dc:creator>
            <pubDate>Wed, 14 Aug 2024 07:21:21 GMT</pubDate>
            <atom:updated>2024-08-14T07:21:21.713Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>This is English translation of the following original blog in Japanese:</strong></p><p><a href="https://cloud.flect.co.jp/entry/2024/05/24/153354">https://cloud.flect.co.jp/entry/2024/05/24/153354</a></p><p>Einstein Discovery is a platform that allows you to build models for regression analysis without any coding. While you need to prepare the input data in advance, the model construction itself can be done with simple operations on Salesforce, and it comes with dashboards to check various metrics and inference processes of the created models.</p><p>On the other hand, Einstein Next Best Action is a feature that allows you to display recommendations on a Lightning Page based on the logic defined in Flow.</p><p>These Einstein services, which are responsible for statistical inference and recommendation display, are complementary and can achieve significant synergy when used in combination. Results of Einstein prediction shown as Einstein Next Best Action will be definitely a smart suggestion following Lightning page composition guidelines.</p><p>In this article, we introduce a use case that combines Einstein Discovery and Einstein Next Best Action. Specifically, we explain how to display the results of an inference performed by Einstein Discovery as recommendations via Einstein Next Best Action.</p><p>As the simplest example of inference, let’s think about a kind of compatibility diagnosis between two Salesforce standard objects, Contacts. Then display the top three candidates as recommendations on the Contact record page.</p><p>The image is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*6HZCDLynwhLNM5gpLbOuvw.png" /></figure><p>We arranged it to promote communications. The recommendation description will include the corresponding Contact’s name and ID, and clicking “Go” will perform some action based on the Contact ID.</p><p>This is achieved with the following configuration:</p><ul><li>Build a model for calculating matching scores with Einstein Discovery</li><li>Calculate the matching scores for all pairs of Contacts with CRM Analytics Data Prep</li><li>Create recommendations for Einstein Next Best Action from the matching scores</li></ul><p>The most difficult part is the step involving Einstein Next Best Action, where it is necessary to work around a big constraints of Einstein Next Best Action to fit this use case. The detail will be explained later.</p><p>Let’s go through each steps from the top.</p><h3><strong>Building a Model with Einstein Discovery</strong></h3><p>First, we need to prepare a model for calculating matching scores. Since input data is required to build the model, we generated it by an appropriate Python script.</p><p>For reference, here is the Python script.</p><pre>import csv<br>import random<br>import uuid<br><br>AGE_MIN = 20<br>AGE_MAX = 60<br>SCORE_NOISE_MAX = 5.0<br>SCORE_NOISE_MIN = -5.0<br>NUM_OF_DATA = 1000<br><br>if __name__ == &#39;__main__&#39;:<br>  with open(&#39;out.csv&#39;, &#39;w&#39;) as f:<br>    fieldnames = [&#39;id&#39;, &#39;age1&#39;, &#39;age2&#39;, &#39;score&#39;]<br>    writer = csv.DictWriter(f, fieldnames=fieldnames, dialect=&#39;unix&#39;)<br>    writer.writeheader()<br>    for i in range(NUM_OF_DATA):<br>      id = uuid.uuid4().hex<br>      age1 = random.randint(AGE_MIN, AGE_MAX)<br>      age2 = random.randint(AGE_MIN, AGE_MAX)<br><br>      # high score if they are around same age<br>      noise = random.uniform(SCORE_NOISE_MIN, SCORE_NOISE_MAX)<br>      score = (AGE_MAX - AGE_MIN) - abs(age1 - age2) + noise<br><br>      writer.writerow({&#39;id&#39;: id, &#39;age1&#39;: age1, &#39;age2&#39;: age2, &#39;score&#39;: score})p</pre><p>It uses a very old-fashioned algorithm that takes the ages of each pair of Contacts and outputs a higher score if the ages are close. Feel free to adjust as needed.</p><p>As long as you have the data, building a model with Einstein Discovery is very easy, and you can easily do it by reading <a href="https://trailhead.salesforce.com/ja/content/learn/modules/einstein-discovery-basics">Trailhead</a>.</p><p>When deploying the model, you will see two options “Connect to a Salesforce Object” and “Deploy without connecting to a Salesforce Object.” In this case, choose the latter. If you choose the former one, you will be restricted to setting the model’s input parameters only from the fields of a single record. However, this time, as it is necessary to input from multiple (two) Contact records into the model, this restriction cannot be accepted.</p><h3><strong>Calculating Matching Scores with CRM Analytics</strong></h3><p>In the next, we perform inference by the model created with Einstein Discovery from the CRM Analytics Data Prep Recipe to calculate the matching scores. There are no particularly difficult points about Data Prep Recipe, and you can easily create it by referring to <a href="https://help.salesforce.com/s/articleView?id=sf.bi_integrate_recipe_create.htm&amp;type=5">this</a> official document.</p><p>The content to be implemented in the Recipe is as follows:</p><ol><li>Perform a cross join of Contacts</li><li>Remove combinations of the same Contacts from the results obtained in step 1</li><li>Apply the Einstein Discovery model inference to the results obtained in step 2</li><li>Save the results obtained in step 3 as a Dataset</li></ol><p>In step 3, CRM Analytics will be linked with Einstein Discovery, but there are no particularly difficult points in the settings, and you can link them by simply adding a Discovery Predict block to the Recipe pipeline and setting the input parameters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*CmiXZK7iho2LQOEsHrUGcQ.png" /></figure><p>For reference, the Recipe pipeline created by us is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*95iCnTiiK3v4CZSubBM7mg.png" /></figure><p>In the Transform block after Predict Score, we adjust API names of a field. When performing a cross join, the API names of the columns from the join source are changed to names like partner.Id that include a .. However, when referring to the Dataset from APEX later, having a . requires a cumbersome handling, so it is corrected here.</p><p>After creating the Recipe, execute it to generate the Dataset.</p><h3><strong>Creating Recommendations for Einstein Next Best Action</strong></h3><p>Finally, it’s the main part. As mentioned at the beginning, this is the most difficult part.</p><p>What makes it so difficult? It is so poor extensibility of a part of Einstein Next Best Action that it is difficult to work around them. As long as you are involved in cloud services, you will encounter such constraints with a certain frequency, but this constraints of Einstein Next Best Action are quite severe and can easily become a showstopper depending on the use case.</p><p>Specifically, in this use case, it is necessary to work around the following two constraints.</p><h4><strong>Cannot Set Dynamic Text in Recommendation Descriptions</strong></h4><p>There is a restriction that only fixed text can be set in the recommendation descriptions. This becomes an obstacle when trying to include information about the top matching Contacts in the description.</p><p>However, this restriction can be circumvented by dynamically generating the recommendations itself from APEX, which seems trivial compared to the next constraint.</p><h4><strong>No Ways to Obtain Information about the Originating Recommendation from the Flow Triggered upon Acceptance</strong></h4><p>It doesn’t make sense, but it’s a fact. How did it come to this…?</p><p>Unfortunately, there is no way to obtain information about the originating recommendation from the Flow triggered when a recommendation is accepted. So, what information can be obtained? Essentially, no information can be obtained. According to the official documentation, the basic premise of Einstein Next Best Action is to process from scratch based solely on the fact that it was triggered.</p><p>The only exception mentioned in the official documentation is a variable called isRecommendationAccepted, which stores a boolean value indicating whether the recommendation was accepted or rejected. However, it is obviously impossible to realize our use case with just this information.</p><p>It seemed like we had hit a dead end… but after some research, we found a breakthrough in the following thread:</p><ul><li><a href="https://trailhead.salesforce.com/ja/trailblazer-community/feed/0D54S00000A8OEQSA3">RecordId to Next Best Action | Salesforce Trailblazer Community</a></li></ul><p>The thread mentions that there is a hidden parameter called recordId in Einstein Next Best Action, which can be used to obtain the ID of the Contact for which the recommendation is displayed. W̶h̶y̶ ̶w̶a̶s̶ ̶t̶h̶i̶s̶ ̶h̶i̶d̶d̶e̶n̶.̶.̶.̶?̶</p><p>Unfortunately, information about the recommendation itself still cannot be obtained, but by using recordId, it is possible to devise an implementation to obtain the IDs of both Contacts related to the recommendation.</p><p>Specifically, define three Flows triggered when a recommendation is accepted, each of which corresponds to the recommendation for the 1st, 2nd, and 3rd highest matching scores. This way, the ranking of the matching score can be identified based on which Flow was triggered. By combining the identified ranking with the recordId, it is possible to determine which Contact is the counterpart.</p><p>The diagram is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ACZQTHBUJ-l6oW1vNoJubQ.png" /></figure><p>With this, all constraints can be circumvented. Now, let’s move on to the specific implementation method.</p><h3><strong>Creating the Flow for When a Recommendation is Accepted</strong></h3><p>As mentioned earlier, create three Flows. But before that, define an APEX Action to obtain the counterpart’s Contact ID from the recordIdand matching score ranking.</p><p>To use the CRM Analytics API from APEX, use the classes in the Wave namespace. For querying the Dataset, it is recommended to read the sample code in <a href="https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_class_wave_QueryBuilder.htm">this</a> official documentation.</p><pre>global class GetPartnerId {<br><br>    private static String DATASET_ID = &#39;(your-dataset-id)&#39;;<br><br>    // NOTE: The ideal approach would be to obtain the currentVersionId as needed via the REST API<br>    //  instead of using a fixed value, but this will be omitted for now.<br>    private static String DATASET_VERSION_ID = &#39;(your-dataset-version-id)&#39;;<br><br>    @InvocableMethod<br>    public static List&lt;String&gt; get(List&lt;Input&gt; inputs) {<br>        String id = inputs[0].id;<br>        Integer targetIndex = inputs[0].targetIndex;<br><br>        List&lt;Record&gt; records = retrieveScores(id);<br>        records.sort(new ScoreComparator());<br><br>        Record target = records[targetIndex];<br>        return new List&lt;String&gt;{target.partnerId};<br>    }<br><br>    private static List&lt;Record&gt; retrieveScores(String id) {<br>        Wave.ProjectionNode[] projs = new Wave.ProjectionNode[]{<br>            Wave.QueryBuilder.get(&#39;partnerId&#39;).alias(&#39;partnerId&#39;)<br>        };<br>        ConnectApi.LiteralJson result = Wave.QueryBuilder.load(DATASET_ID, DATASET_VERSION_ID)<br>            .filter(&#39;Id == &quot;&#39; + id + &#39;&quot;&#39;)<br>            .foreach(projs)<br>            .execute(&#39;q&#39;);<br><br>        JSONParser parser = JSON.createParser(result.json);<br>        Response res = (Response) parser.readValueAs(Response.class);<br><br>        return res.results.records;<br>    }<br><br>    public class ScoreComparator implements Comparator&lt;Record&gt; {<br>        public Integer compare(Record r1, Record r2) {<br>            if (r1.score &lt; r2.score) {<br>                return -1;<br>            }<br>            if (r1.score &gt; r2.score) {<br>                return 1;<br>            }<br>            return 0;<br>        }<br>    }<br><br>    global class Input {<br>        @InvocableVariable<br>        public String id;<br>        @InvocableVariable<br>        public Integer targetIndex;<br>    }<br><br>    public class Response {<br>        public Results results;<br>    }<br><br>    public class Results {<br>        public List&lt;Record&gt; records;<br>    }<br><br>    public class Record {<br>        public String partnerId;<br>    }<br>}</pre><p>Basically, it just queries the Dataset.</p><p>Then, define the three Flows that call the above APEX Action. Note that the targetIndex passed to the APEX Action from each Flow needs to be changed according to the ranking that the Flow is responsible for.</p><h3><strong>Generating Recommendations via APEX Action</strong></h3><p>Since we want to embed information about the top matching Contacts in the description, create the recommendations via APEX. Specifically, create an Autolaunched Flow and call the APEX Action from there to create the recommendations.</p><p>In this demo, we have implemented an APEX that takes a target Contact ID (who the recommendation will be displayed for) from the Flow, and generates recommendations for the top three matching scores of that Contact.</p><pre>global class CreateRecommendation {<br><br>    private static String DATASET_ID = &#39;(your-dataset-id)&#39;;<br><br>    // NOTE: The ideal approach would be to obtain the currentVersionId as needed via the REST API<br>    //  instead of using a fixed value, but this will be omitted for now.<br>    private static String DATASET_VERSION_ID = &#39;(your-dataset-version-id)&#39;;<br><br>    @InvocableMethod<br>    public static List&lt;String&gt; get(List&lt;Id&gt; ids) {<br>        String id = ids[0];<br><br>        List&lt;Record&gt; records = retrieveScores(id);<br>        if (records.size() &lt; 1) {<br>            return new List&lt;String&gt;{&#39;No Result&#39;};<br>        }<br><br>        records.sort(new ScoreComparator());<br><br>        List&lt;Record&gt; top3 = new List&lt;Record&gt;();<br>        for (Integer i = 0; i &lt; records.size() &amp;&amp; i &lt; 3; i++) {<br>            top3.add(records[i]);<br>        }<br><br>        List&lt;Recommendation&gt; recommendations = new List&lt;Recommendation&gt;();<br>        for (Integer i = 0; i &lt; top3.size(); i++) {<br>            Record record = top3[i];<br>            Recommendation recommendation = new Recommendation();<br>            recommendation.Name = &#39;your_recommendation_&#39; + record.id + &#39;_&#39; + record.partnerId;<br>            recommendation.Description = &#39;Talk with &#39; + record.partnerName + &#39; (ID: &#39; + record.partnerId + &#39;)&#39;;<br>            recommendation.ActionReference = &#39;your_flow_api_name_&#39; + String.valueOf(i);<br>            recommendation.AcceptanceLabel = &#39;Go&#39;;<br>            recommendation.RejectionLabel = &#39;No thanks&#39;;<br>            recommendations.add(recommendation);<br>        }<br><br>        insert recommendations;<br><br>        return new List&lt;String&gt;{recommendations.toString()};<br>    }<br><br>    private static List&lt;Record&gt; retrieveScores(String id) {<br>        Wave.ProjectionNode[] projs = new Wave.ProjectionNode[]{<br>            Wave.QueryBuilder.get(&#39;Id&#39;).alias(&#39;id&#39;),<br>            Wave.QueryBuilder.get(&#39;partnerId&#39;).alias(&#39;partnerId&#39;),<br>            Wave.QueryBuilder.get(&#39;partnerName&#39;).alias(&#39;partnerName&#39;)<br>        };<br>        ConnectApi.LiteralJson result = Wave.QueryBuilder.load(DATASET_ID, DATASET_VERSION_ID)<br>            .filter(&#39;Id == &quot;&#39; + id + &#39;&quot;&#39;)<br>            .foreach(projs)<br>            .execute(&#39;q&#39;);<br><br>        JSONParser parser = JSON.createParser(result.json);<br>        Response res = (Response) parser.readValueAs(Response.class);<br><br>        return res.results.records;<br>    }<br><br><br>    public class ScoreComparator implements Comparator&lt;Record&gt; {<br>        public Integer compare(Record r1, Record r2) {<br>            if (r1.score &lt; r2.score) {<br>                return -1;<br>            }<br>            if (r1.score &gt; r2.score) {<br>                return 1;<br>            }<br>            return 0;<br>        }<br>    }<br><br>    public class Response {<br>        public Results results;<br>    }<br><br>    public class Results {<br>        public List&lt;Record&gt; records;<br>    }<br><br>    public class Record {<br>        public String id;<br>        public String partnerId;<br>        public String partnerName;<br>    }<br>}</pre><p>In the Autolaunched Flow, obtain an appropriate Contact ID and pass it to the APEX Action.</p><p>This time, we won’t cover automatically triggering the Flow, so we’ll manually execute it to generate the recommendations.</p><h3><strong>Creating the Recommendation Strategy Flow</strong></h3><p>Finally, the finishing touch, but there are no particularly difficult points. Just search for the recommendations based on the recordId received as input to the Flow.</p><p>If you use the sample code as it is, you can search for records that include your_recommendation_(recordId) in their name to collectively obtain the necessary recommendations. Then, assign them to outputRecommendations to complete.</p><p>Don’t forget to incorporate the Einstein Next Best Action component into the Contact record page in the Lightning App Builder.</p><h3><strong>Conclusion</strong></h3><p>Thus, we were able to realize a recommendation display function in the style of a matching service with the configuration of CRM Analytics + Einstein Discovery + Einstein Next Best Action.</p><p>The key points this time are generally related to Einstein Next Best Action:</p><ul><li>Cannot obtain information about the originating recommendation from the Flow triggered upon acceptance</li><li>The only parameter available in the Flow is the hidden parameter recordId</li><li>The function to display the top N items can be realized through ingenuity</li></ul><p>Note that although we wrote “top N items,” there is a restriction that only up to four recommendations can be displayed, so in practice, it is limited to displaying the top four items.</p><p>We like the actual recommendation display screen, so post it once more at the end. :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*6HZCDLynwhLNM5gpLbOuvw.png" /></figure><p>That’s all. Thank you for reading to the end.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1a7e4361f08" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>